Search code examples
cnewlinestring-formattingfgets

C: How to make fgets read a \n line break from a file?


I have a program (console), where I put all the text in a separate .txt file.

I use fgets() to read a string from the file, but when the file contains a \n and I later print the string, it prints \n instead of a linebreak

Here is an example:

FILE* fic = NULL;
char str[22]; //str is the string we will use

//open the file
fic = fopen ("text.txt", "r");

//read from the file
fgets(str, size, fic);

printf(str);

If this is what I have in my text.txt:

This is \n an example

However what comes out on the console is

This is \n an example

Instead of

This is 
 an example

Edit: in the file it's written as \n. I also tried addint \ or \t in the file but it would print \ and \t instead of a tabulation or a single back-slash


Solution

  • fgets just sees the \ and the n as normal characters. You have to translate it by your self to a linefeed character. Maybe with help of strstr() or similar.