2017-09-19 158 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'可以有效地創建一個文件。 –

相關問題