Search code examples
cfopenfwrite

Opening a file using fopen with same flag in C


I could not understand the output of this code?

int main()
{
    FILE* f, *f1;
    f = fopen("mytext", "w");
    if ((f1 = fopen("mytext", "w")) == 0)
       printf("unable\n");
    fprintf(f, "hello\n");
    fprintf(f1, "hi\n");
    return 0;
}

OUTPUT IS hello in mytext file. Why is it not being written? "unable" is not printed to stdout.


Solution

  • You have 2 FILE* open to the same file, pointing at the beginning of the file, so one of the writes overwrites the other.

    Note also that FILE* are normally buffered, so these small strings actually gets written to the file when you fclose() or fflush() the FILE*. Since you do neither, the system will do it when the application exits , so which write gets overwritten depends on which file the system closes first.

    If you open the 2 files in append mode , fopen("mytext","a");, you'll see different result, but you'll need to fflush() the FILE* when you want to make sure operating on the other FILE* doesn't cause interleaved output. And writing to the same file from different processes/threads will take more care, e.g. some form of file locking.