2017-09-19 159 views
-1

我想检查文件是否存在,并试图使用下面的函数检查在C++中的文件是否存在,而无需创建文件

#include <fstream> 

bool DoesFileExist(const std::string& filename) { 
    std::ifstream ifile(filename.c_str()); 
    return (bool)ifile; 
    } 

但是,它似乎并没有正常工作,因为而不是检查存在,一个文件被创建!这里有什么问题?

请注意,我被迫使用C++ 98标准,不能使用#include <sys/stat.h>#include <unistd.h>作为接受的答案建议here.

+1

如果可能的话,学习C++ 11; C + 98真的过时了。仔细阅读[std :: ifstream](http://en.cppreference.com/w/cpp/io/basic_ifstream)的文档。发布一些[MCVE](https://stackoverflow.com/help/mcve)。您显示的代码可能不像您所说的那样行为 –

+1

[这个答案](https://stackoverflow.com/a/6297560/4143855)没有帮助吗? 'std :: fstream ifile(filename.c_str(),ios_base :: out | ios_base :: in);' – Tas

+0

不可重复https://ideone.com/Z4c2EW –

回答

2

您可以使用这些功能,看文件是否存在

bool DoesFileExist (const std::string& name) { 
    ifstream f(name.c_str()); 
    return f.good(); 
} 

bool DoesFileExist (const std::string& name) { 
    if (FILE *file = fopen(name.c_str(), "r")) { 
     fclose(file); 
     return true; 
    } else { 
     return false; 
    } 
} 

bool DoesFileExist (const std::string& name) { 
    return (access(name.c_str(), F_OK) != -1); 
} 

bool DoesFileExist (const std::string& name) { 
    struct stat buffer; 
    return (stat (name.c_str(), &buffer) == 0); 
} 
+1

适合使用fopen ()'。不幸的是,'std :: ifstream'可以有效地创建一个文件。 –

相关问题