0%
C/C++ Check File Exists
- 主要有幾種方式
- ifstream (C++)
- FILE (C)
- access()
- std::filesystem::exists() (C++17)
- boost::filesystem::exists() (Boost)
fstream
is_open
- 未必真的是不存在,有可能只是打不開
1 2 3 4
| fstream fs(path.c_str(),ios::out); //fs.open(path.c_str(),ios::out); 使用open開檔
if(fs.is_open()){
|
good()
- 不過goodbit如果為false有三種可能
- eofbit 讀到檔案結尾
- failbit 可以讀取,但是有些內部的邏輯上錯誤,如今天我讀檔時,我預計讀到文字,他卻給我數字
- badbit 檔案可能損毀導致無法讀取檔案中串流
fopen
1 2 3 4 5 6
| FILE *fp; if (fp = fopen(path.c_str(), "r")) { fclose(fp); return true; } return false;
|
access
1 2 3 4
| if((access(path.c_str(), F_OK)) != 0) { return false; } return true;
|
stat
1 2 3 4 5
| struct stat info; if (stat(path.c_str(), &info) == 0) { return true; } return false;
|
std::filesystem::exists() (C++17)
1 2 3 4
| if (std::filesystem::exists(path.c_str())) { return true; } return false;
|
boost::filesystem::exists() (Boost)
- #include <boost/filesystem.hpp>
1 2 3 4
| if (boost::filesystem::exists(path.c_str())) { return true; } return false;
|
speed
- Results for total time to run the 100,000 calls averaged over 5 runs,
Method |
Time |
exists_test0 (ifstream) |
0.485s |
exists_test1 (FILE fopen) |
0.302s |
exists_test2 (posix access()) |
0.202s |
exists_test3 (posix stat()) |
0.134s |
reference