V
V
Vi Vola2020-06-04 12:24:56
linux
Vi Vola, 2020-06-04 12:24:56

Why doesn't fwrite return an error when deleting a file?

There is such a very simple code that adds data to the end of the file once a second.

int main()
{
        FILE* file = fopen("test.file", "a");
        int i = 0;
        char str[100];

        while (1) {
                sprintf(str, "heeeey %d\n", i);
                int w = fwrite(str, sizeof(char), strlen(str), file);
                int fl = fflush(file);
                printf("fwrite = %d, fflush = %d \n", w, fl);
                sleep(1);
                ++i;
        }

        return EXIT_SUCCESS;
}


I run this program, I see that fwrite returns the number of bytes written, the file has been created and the data appears. While the program is running, I delete the file and see that fwrite continues to return the number of bytes written, while the file does not exist, and it is not recreated. Though it would seem logical that I should get an error. fflush is also silent.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2020-06-04
@hakain

While the program is running, I delete the file and see that fwrite continues to return the number of bytes written, while the file does not exist, and it is not recreated.

You do not delete the file, but only its name from the directory. The file remains until the last handle pointing to it is closed. All processes that opened the file before its name was removed will have access to it until then. You can verify this by looking at /proc/<pid>/fdyour process.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question