c - 读取文件 - fgets 读取\n 不是的地方

标签 c

我正在编写此代码来读取包含一个或多个矩阵的文件。 还有第一行包含有关每行上方矩阵的一些信息。

这是代码:

void loadfile(char *filename, maps **head, maps **tail){

    FILE *file;
    maps *aux;
    char buffer[MAX_CHAR];
    bool flag = true;
    int current_line = 1;

    /* open file */
    file = openfile(filename, "r");

    while(fgets(buffer, MAX_CHAR, file) != NULL){

        while(strcmp(buffer, "\n") == 0){
            fgets(buffer, MAX_CHAR, file);
            flag = true;
            printf("HERE\n");   
        }

        if(flag == true){
            printf("Dayum\n");
            aux = emptymap();
            settings(buffer, aux);
            managelist(head, tail, aux);
            flag = false;
            current_line = 1;
        }else{
            fillboard(buffer, aux, current_line);
            current_line++;
        }
    }

    /* close file */
    fclose(file);
}

For some files it works okay, like this one:

But for others like this, it doesn't:

它毫无理由地卡在这个 while 循环中:

 while(strcmp(buffer, "\n") == 0){
        fgets(buffer, MAX_CHAR, file);
        flag = true;
        printf("HERE\n");   
    }

我需要帮助,因为我真的不明白为什么会发生这种情况!

最佳答案

不会检查对 fgets 的内部调用(在 while(strcmp) 循环内)。并且,引用 C11 (N1570) 7.21.7.2/3:

If end-of-file is encountered and no characters have been read into the array, the contents of the array remain unchanged and a null pointer is returned.

因此,如果缓冲区仅包含 '\n' 并且这是文件中的最后一个字符,您将永远陷入循环,因为缓冲区不会被覆盖。

关于c - 读取文件 - fgets 读取\n 不是的地方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50238511/

相关文章:

c - 保存字符串反转

无法使用 CMAKE 构建 Makefile,未指定编译器

c - 这是未定义的行为(使用字符串文字)

C:我无法让这个示例税收计划发挥作用

c - 在嵌入式平台上,使用 unsigned int 代替(隐式签名)int 是否更有效?

c - 内存映射文件偏移量低

c - 如何在 C 中将整数转换为数字数组?

C++ 用宏替换函数

c - 嵌入DHT11,第一次打印后温度变为0

c - 结构填充