简体   繁体   中英

How to read special characters from a text file?

I have a text file with some special characters ( \n , \t , etc). The question is: is there anyway to print a new line or a tab instead just printing the string \n or \t ?

int main(){

    char line[10];

    FILE*file= fopen("file.txt", "r"); // txt content => "line 1 \n line 2 \n line 3"
    if (file != NULL){
        while (fgets(line, 10, file) != NULL)
            printf("%s", line);
    }
    return 0;
}

Call this function:

void cleanUp(char * line) {
    int x;
    int y = 0;
    for (x = 0; x < strlen(line) - 1; x++) {
        if (line[x] == '\\') {
            if (line[x + 1] == 'n') {
                line[y++] = '\n';
                x = x + 2; /* if there is always a space after the \n otherwise x++ */
                continue;
            }
            if (line[x + 1] == 't') {
                line[y++] = '\t';
                x = x + 2; /* if there is always a space after the \t otherwise x++ */
                continue;
            }
        }
        line[y++] = line[x];
    }
    line[y++] = '\n';
    line[y] = '\0';
}

before printing line .

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