fwrite() succeeded after fclose()

為{幸葍}努か 提交于 2020-01-05 10:34:28

问题


I've encountered a strange behavior that is fwrite()succeeds after I close the stream with fclose() but the file is not overwritten as fflush() fails.

My code is:

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

It gives the following output:

Count of written objects into the file: 1 
Variable success: -1 
Flush did not succeed. 
: Bad file descriptor

How can fwrite() succeed when the stream is closed? Can fwrite() write on the closed stream? Could you explain it to me?


回答1:


Attempting to do any operations on a file after it has been closed, you are dealing with undefined behaviour.

The library implementer assumes that it is the responsibility of the caller to issue the calls in a certain order, hence the library may or may not try to validate the cases where that isn't true. Validation for such cases is ignored mostly for performance and reducing the code size.

The same thing will happen if you attempt to write to a memory location that has been previously free'd. Even though it may seem as if everything works correctly, you are invoking undefined behaviour.

Technically speaking, in the particular case it shouldn't be possible for the write to succeed, because the library function fclose will most probably call the close system call on the underlying descriptor, and any subsequent write system calls to that descriptor (eventually invoked by fwrite) should fail because it will be rejected by the kernel.



来源:https://stackoverflow.com/questions/23954102/fwrite-succeeded-after-fclose

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!