繁体   English   中英

C:如何使fget从文件中读取\\ n换行符?

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

我有一个程序(控制台),将所有文本放在单独的.txt文件中。

我使用fgets()从文件中读取字符串,但是当文件包含\\ n并稍后打印该字符串时,它将打印\\ n而不是换行符

这是一个例子:

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);

如果这是我的text.txt中的内容:

This is \n an example

但是,控制台上显示的是

This is \n an example

代替

This is 
 an example

编辑:在文件中,其写为​​\\ n。 我也尝试在文件中使用addint \\或\\ t,但是它将打印\\和\\ t而不是列表或单个反斜杠

fgets只是将\\和n视为普通字符。 您必须自行将其转换为换行符。 也许借助strstr()或类似方法。

这是因为编译器在解析代码时会处理字符串和字符文字中的转义字符。 库或所有字符串的运行时代码中都不存在它。

例如,如果要翻译从文件中读取的两个字符\\n ,则需要在代码中自行处理。 例如,通过逐个字符遍历字符串并查找'\\\\'后跟'n'

编译器正在扫描文本文件,并将数据/文本按原样存储在str字符串中。 编译器不将\\n用作转义序列。 因此,如果想在出现\\n时转到下一行,则应该逐字符进行扫描,如果出现\\n ,则应该使用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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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