简体   繁体   中英

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

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.

That's because escape characters in string and character literals are handled by the compiler when it parses your code. It's not something that exists in the library or run-time code for all strings.

If you want to translate eg the two characters \\n that you read from a file, then you need to handle it yourself in your code. For example by going over the string character by character and looking for '\\\\' followed by 'n' .

The compiler is scanning the text file and storing the data/text as it is in str string. The compiler does not take \\n as an escape sequence. So if you want to go to the next line whenever \\n appears then you should scan character by character, and if \\n appears you should printf("\\n") .

#include <stdio.h>

int main(){
    char str[30];
    int i = 0;
    FILE *fic = NULL;
    fic = fopen("text.txt", "r");
    while(!feof(fic)){
        str[i++] = getc(fic);
        if(i > 30){    //Exit the loop to avoid writing outside of the string
            break;
        }
    }
    str[i - 1] = '\0';
    fclose(fic);

    for(i = 0; str[i] != '\0'; i++){
        if(str[i] == 'n' && str[i - 1] == '\\'){
            printf("\n");
            continue;
        }
        if(str[i] == '\\' && str[i + 1] == 'n'){
            printf("\n");
            continue;
        }
        printf("%c",str[i]);
    }
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM