c - 如何从文本文件中读取特殊字符?

标签 c

我有一个包含一些特殊字符(\n\t 等)的文本文件。问题是:是否有办法打印新行或制表符,而不是仅打印字符串 \n\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;
}

最佳答案

调用此函数:

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';
}

打印之前。

关于c - 如何从文本文件中读取特殊字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58634850/

相关文章:

C++,嵌入式 Linux,用于视频 HDMI 输入/输出

c - 在运行时重定向一个 c 函数并调用原始函数

c - Visual Studio 2017 srand() 崩溃(在线编译器有效)

c++ - 重命名(别名)数组元素 C

c - 定义基本的 alloc 函数

c - 确定进程是子进程还是父进程(不使用 fork 的返回值)

c++ - 从无符号整数类型样式转换。这种风格好吗?

c - 在 c 中打印 1 - 999 之间的所有阿姆斯壮数字

c - 为什么建议在 scanf 格式字符串中添加前导空格?

c - 运行时数据和代码内存大小估计