c++覆盖已经打开的文件
我正在使用 ifstream
打开一个文件来检查它是否存在。然后我关闭它并使用 ofstream
打开它来写入它,我认为设置 ios::trunc
标志允许我覆盖它。
不过,我希望能够保持文件存在(如果存在),但我使用了 ifstream 来打开它,这是否意味着在关闭并重新打开之前我无法写入该文件使用fstream还是ofstream?我一开始就没有使用 fstream,因为它无法告诉我该文件是否已经存在。
I am opening a file with ifstream
to check if it exists. Then I close it and open it with ofstream
to write to it, and I think setting ios::trunc
flag allows me to overwrite it.
However I'd like the ability to keep the file open if it exists, but I used an ifstream
to open it so does that mean I can't write to the file till I close and re-open using fstream
or ofstream
? I didn't use fstream
to begin with because that wouldn't tell me if the file was already there or not.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需在文件上打开一个读写
fstream
即可。您可以通过查找末尾并查看偏移量是否为非零来测试文件以前是否存在(并且非空)。如果是这样,则该文件存在,您可以使用它执行任何操作。如果不是,则该文件不存在或为空。假设您不需要区分这两种情况,则可以像它不存在一样继续操作。例如:
Just open a read-write
fstream
on the file. You can test if the file previously existed (and was non-empty) by seeking to the end and seeing if you're at a non-zero offset. If so, the file existed, and you can do whatever with it. If not, the file didn't exist or was empty. Assuming you don't need to distinguish between those two cases, you can then proceed as if it did not exist.For example:
设置
ios::trunc
会删除文件以前的内容。尝试在没有此设置的情况下打开文件;仅使用“写入”设置。
The setting
ios::trunc
erases previous contents of the file.Try opening the file without this setting; with only the 'write' setting.
这是一个非常严重的问题 - 竞争条件 - 如果有人设法在关闭和重新打开之间对该文件执行某些操作怎么办?不幸的是 iostream 没有提供任何解决该问题的方法 - 您可以使用 cstdio FILE。如果您想翻转文件(如果存在)或创建新文件(如果不存在),请使用 fopen(name, "w")。如果您想转换文件(如果存在)或失败,那么标准库似乎没有什么可提供的,您应该转到其他库或平台特定的函数,例如 windows.h 中的 OpenFile
this is touching very serios problem - race conditions - what if somebody manages to do something with this file between closing and reopening? unfortunately iostream does not provide any means of resolving that issue - you can use cstdio FILE. If you want to turncate file if exists or create new one if not use fopen(name, "w"). If you want to turncate file if it exists or fail otherwise, then it seems standard library has nothing to offer, and you should go to other libraries or platform specific functions like OpenFile in windows.h