如何在创建文件之前测试一个文件是否存在 [英] How to test if a file exists before creating it

查看:96
本文介绍了如何在创建文件之前测试一个文件是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想看看文件是否存在。如果它不存在,那么我想创建它。我正在使用Linux。

解决方案

您无法可靠地做到这一点。在您检查文件是否存在以及创建文件时,可能会有另一个进程创建它。



您应该继续创建文件。根据您要做的更大的事情,您可能需要这些选项中的一个,以便在文件已存在的情况下执行该操作:


  • 修改以前的内容: open(file,O_RDWR | O_CREAT,0666)

  • 清除以前的内容: open(file,O_WRONLY | O_CREAT | O_TRUNC,0666
  • 附加到前面的内容: open (file,O_WRONLY | O_CREAT | O_APPEND,0666)

  • 操作失败: open(file,O_WRONLY | O_CREAT | O_EXCL,0666)



其中大多数 iostream 界面。也许还有一种方法可以在你从 open 获得的文件描述符周围打包一个iostream,具体取决于你拥有哪个C ++库。



另外,我应该提到,如果你想自动替换文件的内容(所以没有进程看到一个不完整的文件),唯一的方法是写出新内容添加到文件,然后使用 rename 将其移动到旧文件中。


I would like to see if a file exists. If it does not exists, then I would like to create it. I am using Linux by the way.

解决方案

You can't do that reliably. Between when you check to see if the file exists and when you create it, another process may create it.

You should just go ahead and create the file. Depending on the larger thing you're trying to do, you might want one of these options for what to do if the file already exists:

  • modify the previous contents in place: open("file", O_RDWR|O_CREAT, 0666)
  • erase the previous contents: open("file", O_WRONLY|O_CREAT|O_TRUNC, 0666)
  • append to the previous contents: open("file", O_WRONLY|O_CREAT|O_APPEND, 0666)
  • fail the operation: open("file", O_WRONLY|O_CREAT|O_EXCL, 0666)

Most of these, but unfortunately not all, have equivalents at the higher level iostream interface. There may also be a way to wrap an iostream around the file descriptor you get from open, depending on which C++ library you have.

Also, I should mention that if you want to atomically replace the contents of a file (so no process ever sees an incomplete file) the only way to do that is to write out the new contents to a new file and then use rename to move it over the old file.

这篇关于如何在创建文件之前测试一个文件是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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