【问题标题】:How to check if file exists in directory? [duplicate]如何检查目录中是否存在文件? [复制]
【发布时间】:2014-03-06 11:44:24
【问题描述】:

我是 C++ 的新手,我对检查文本文件是否存在的所有不同方法感到有点困惑/不知所措。

我创建了一个文本文件:

ofstream myfile;
myfile.open("actFile.txt");

我可以在目录中看到。但是我将如何使用它来查看它是否已经存在?

这行得通吗?

ofstream myfile;
if (myfile.good())
{
  // read, write
} else
{
  myfile.open("actFile.txt");
}

【问题讨论】:

标签: c++ file file-io directory file-exists


【解决方案1】:

使用is_open() 方法:

std::string filename = "myfile";
std::ifstream ifile(filename.c_str());

if (!ifile.is_open()) {
    std::cerr << "There was a problem opening the input file" << std::endl;
}

参考: http://www.cplusplus.com/reference/fstream/fstream/is_open/

【讨论】:

    猜你喜欢
    • 2012-05-17
    • 1970-01-01
    • 2012-02-06
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 2018-09-27
    • 2014-03-30
    • 2012-07-02
    相关资源
    最近更新 更多