我正在编写此代码来读取包含一个或多个矩阵的文件。 还有第一行包含有关每行上方矩阵的一些信息。
这是代码:
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/