Linux C 应用程序读取正在修改的文件

huangapple go评论62阅读模式
英文:

Linux C application reading file that is being modified

问题

我有一个在Linux上的简单的C应用程序,它使用fopen打开一个文件,并开始逐行使用fgets读取其内容。在此过程中,另一个应用程序覆盖该文件的内容,而不锁定它。

只要文件没有使用fclose关闭,我的应用程序是否保证能够访问文件的旧内容,而不包括新内容?通过对小文件进行简单测试,答案似乎是'是',我还没有找到不成立的情况。然而,也许对于足够大的文件和/或其中的活动,这种情况可能会发生。

如果这个论坛中有人确切知道是这样还是那样,我会非常感兴趣知道。

英文:

I have a simple C application in Linux that opens a file with fopen and starts reading its contents, one line at a time, with fgets. While this is in process, a separate application overwrites the contents of that file, without locking it.

Is my application guaranteed to have access to the old contents of the file, and nothing from the new contents, as long as the file is not closed with fclose? A simple test with small files shows that the answer is 'yes', in that I have not been able to come up with instances in which it was not true. However, maybe with sufficiently large files and/or activity in them, such things will happen.

If anybody in this forum knows for sure one way or the other I would be very interested to know.

答案1

得分: 1

No.

您的应用程序不能保证只看到文件的原始内容,即使文件没有使用 fclose 关闭。

如果您使用 fopen(),数据会被缓冲。通过 setbuf(fp, NULL) 关闭缓冲,然后再进行测试。

英文:

> Is my application guaranteed to have access to the old contents of the file, and nothing from the new contents, as long as the file is not closed with fclose?

No.

Your application does not have any guarantees that it will see the original contents of the file if the file changes.

> A simple test with small files shows that the answer is 'yes', in that I have not been able to come up with instances in which it was not true.

If you're using fopen(), the data is buffered. Turn off buffering with setbuf(fp, NULL) and then try your test again.

huangapple
  • 本文由 发表于 2023年2月27日 07:18:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75575606.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定