我遇到了一种奇怪的行为,在我用fwrite()关闭流之后,fclose()成功了,但是文件没有被覆盖,因为fflush()失败了。
我的代码是:
int main(int argc, char* argv[])
{
FILE* file = fopen("file.txt", "w");
if(!file) perror("Cannot open the file.\n");
char text[] = "1234567";
fclose(file);
int count_of_written_objects = fwrite(text, sizeof(text),1, file);
printf("Count of written objects into the file: %d \n", count_of_written_objects);
if(count_of_written_objects != 1) perror("Not expected count of objects was written.\n");
int success = fflush(file);
printf("Variable success: %d \n", success);
if(success == EOF) perror("Flush did not succeed. \n");
return 0;
}它提供了以下输出:
Count of written objects into the file: 1
Variable success: -1
Flush did not succeed.
: Bad file descriptor当流关闭时,fwrite()如何成功?fwrite()可以在封闭流上写入吗?你能给我解释一下吗?
发布于 2014-05-30 12:05:46
试图在文件关闭后对其执行任何操作,您将处理未定义的行为。
库实现者假定调用者有责任按一定的顺序发出调用,因此库可能尝试验证不正确的情况,也可能不尝试验证。为了提高性能和减少代码大小,忽略了对此类情况的验证。
如果您试图写入以前是freed的内存位置,也会发生同样的情况。尽管看起来一切看起来都正常,但您正在调用未定义的行为。
从技术上讲,在特定的情况下,写入不可能成功,因为库函数fclose很可能会调用底层描述符上的close系统调用,任何后续的write系统调用(最终由fwrite调用)都应该失败,因为它将被内核拒绝。
https://stackoverflow.com/questions/23954102
复制相似问题