fclrite()在fclose()之后成功

And*_* B. 1 c fwrite fclose

我在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;
}
Run Code Online (Sandbox Code Playgroud)

它给出了以下输出:

Count of written objects into the file: 1 
Variable success: -1 
Flush did not succeed. 
: Bad file descriptor
Run Code Online (Sandbox Code Playgroud)

fwrite()流关闭后如何成功?可以fwrite()在封闭的流上写吗?你能解释一下吗?

Bla*_*iev 6

在文件关闭后尝试对文件执行任何操作时,您正在处理未定义的行为.

库实现者假定调用者有责任以特定顺序发出调用,因此库可能会也可能不会尝试验证不正确的情况.对于此类情况的验证主要是因为性能和减小代码大小而被忽略.

如果您尝试写入之前已经存在的内存位置,也会发生同样的事情free.尽管看起来好像一切正​​常,但您正在调用未定义的行为.

从技术上讲,在特定情况下,写入不可能成功,因为库函数fclose很可能会调用close底层描述符上的系统调用,并且write对该描述符的任何后续系统调用(最终被调用fwrite)都应该失败因为它会被内核拒绝.