Opening a file using fopen with same flag in C

2020-04-10 02:56发布

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.

标签: c fopen fwrite
2条回答
Summer. ? 凉城
2楼-- · 2020-04-10 03:36

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.

查看更多
家丑人穷心不美
3楼-- · 2020-04-10 03:36

YOu have 2 file pointers trying to open a file in write mode at the same time. *f successfully opens the file and acquire the lock to the file. In the code the file is not close and another pointer is trying to open the same file in write mode and fails as the lock is not acquired. fopen() doesnt necessarily return 0 when it fails. When a fopen() fails it returns 0 or a negative value. In this case you are only checking for f1 == 0 which may not be true even if fopen for pointer f1 fails and hence unable is not printed to the console. Going ahead, f has a valid open file is write mode hence "hello" gets written to the file. But when you are trying to write "hi" to the same file but using a different pointer which is not initialised, so the fprintf fails. Hence only "hello" is written to the file and "hi" fails.

Proper usage would be to open the file write "hello" close the file and then reopen it again in write mode and the write "hi". In this case you will only see "hi" as it will overwrite "hello".

查看更多
登录 后发表回答