打开使用的fopen在C相同的标志文件 [英] Opening a file using fopen with same flag in C

查看:176
本文介绍了打开使用的fopen在C相同的标志文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白这个code的输出?

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

输出你好在MYTEXT文件。为什么它没有被写入? 无法不打印到标准输出

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

推荐答案

您有2个FILE *开到同一个文件,在文件的开头指出的,所以写的一个覆盖等。

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

还要注意FILE *通常缓冲,所以这些小弦实际上得到写入文件时,你FCLOSE()或fflush()文件*。既然你没有做,系统将做到这一点,当应用程序退出,所以这写被覆盖取决于哪个文件系统关闭第一。

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.

如果您在追加模式打开2个文件,的fopen(MYTEXT,A); ,你会看到不同的结果,但你需要当你想确保另一FILE *操作不会导致交错式输出到fflush()文件*。和写作,从不同的进程相同的文件/线程将采取更多的照顾,例如某种形式的文件锁定。

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.

这篇关于打开使用的fopen在C相同的标志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆