检查C++中是否存在文件的最佳方法是什么?(跨平台)

c0m*_*0m4 95 c++ file-io file

我已经阅读了什么是检查C中是否存在文件的最佳方法的答案(跨平台),但我想知道是否有更好的方法来使用标准的c ++库?最好不要试图打开文件.

这两个stataccess是几乎ungoogleable.我#include该怎么用?

And*_*son 159

使用boost :: filesystem:

#include <boost/filesystem.hpp>

if ( !boost::filesystem::exists( "myfile.txt" ) )
{
  std::cout << "Can't find my file!" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

  • Boost是一个库,其中最终将成为C++标准库的一部分.许多参与提升的人都是参与C++标准的人.因此,提升不仅仅是*任何*第三方库.如果您使用C++进行编程,则*应该*已经安装了boost! (88认同)
  • 似乎有点急于安装一个巨大的第三方库来做一些*应该*简单的事情 (67认同)

rle*_*lut 41

注意竞争条件:如果文件在"存在"检查和打开时间之间消失,程序将意外失败.

最好去打开文件,检查失败,如果一切都好,那么对文件做一些事情.对于安全性至关重要的代码,它更为重要.

有关安全性和竞争条件的详细信息:http: //www.ibm.com/developerworks/library/l-sprace.html


Mat*_*tyT 30

我是一个快乐的推动用户,肯定会使用Andreas的解决方案.但是,如果您无法访问boost库,则可以使用流库:

ifstream file(argv[1]);
if (!file)
{
    // Can't open file
}
Run Code Online (Sandbox Code Playgroud)

它不像boost :: filesystem :: exists那么好,因为文件实际上会被打开...但是那通常是你想要做的下一件事.

  • 但是使用此代码,如果您没有该文件的权限,您也会跳转到if子句,尽管它存在.在大多数情况下,这无关紧要,但仍值得一提. (15认同)

act*_*.se 11

如果跨平台足以满足您的需求,请使用stat().它不是C++标准,而是POSIX.

在MS Windows上有_stat,_stat64,_stati64,_wstat,_wstat64,_wstati64.

  • **NOT USING BOOST** 的好答案+1,因为它有点矫枉过正,但是从这里提供的内容中写出来并不是一件容易的事,所以我只是发布了一个答案。请检查一下。 (2认同)

Rob*_*Rob 9

怎么样access

#include <io.h>

if (_access(filename, 0) == -1)
{
    // File does not exist
}
Run Code Online (Sandbox Code Playgroud)


Sam*_*mer 9

另一种可能性good()是在流中使用该函数:

#include <fstream>     
bool checkExistence(const char* filename)
{
     ifstream Infield(filename);
     return Infield.good();
}
Run Code Online (Sandbox Code Playgroud)


Alb*_*rtM 8

如果你的编译器支持 C++17 你不需要 boost,你可以简单地使用 std::filesystem::exists

#include <iostream> // only for std::cout
#include <filesystem>

if (!std::filesystem::exists("myfile.txt"))
{
    std::cout << "File not found!" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)


fiz*_*zer 7

我会重新考虑试图找出文件是否存在.相反,您应该尝试以您打算使用它的相同模式打开它(在标准C或C++中).知道文件是否存在有什么用处,比如说,当你需要使用它时它是不可写的?