简体   繁体   中英

fwrite() succeeded after fclose()

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM