c++判斷文件是否存在

轉載https://blog.csdn.net/guotianqing/article/details/100766120
c++ 判斷文件是否存在的幾種方法
一般而言,下述方法都可以檢查文件是否存在:

使用ifstream打開文件流,成功則存在,失敗則不存在
以fopen讀方式打開文件,成功則存在,否則不存在
使用access函數獲取文件狀態(tài),成功則存在,否則不存在
使用stat函數獲取文件狀態(tài),成功則存在,否則不存在

代碼如下:

#include <sys/stat.h>
#include <unistd.h>
#include <string>
#include <fstream>

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

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

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

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

參考資料中有性能測試對比,結果表明,使用 stat() 函數的方式性能最好。

# Results for total time to run the 100,000 calls averaged over 5 runs,

Method exists_test0 (ifstream): **0.485s**
Method exists_test1 (FILE fopen): **0.302s**
Method exists_test2 (posix access()): **0.202s**
Method exists_test3 (posix stat()): **0.134s**

boost庫

boost.filesystem在發(fā)生錯誤的時候會拋出異常,但是在大部分情況下這些異常是可以忽略的,例如,在檢查文件是否存在的時候,發(fā)生錯誤可以等同于文件不存在。

雖然boost.filesystem也提供了重載函數,通過輸出參數返回錯誤來代替異常,但是在每個調用點都得定義一個輸出參數,稍顯麻煩。

所以,為了簡化客戶代碼,我們實現了一些包裝函數,如下所示:

bool IsFileExistent(const boost::filesystem::path& path) {
    boost::system:error_code error;
    return boost::filesystem::is_regular_file(path, error);
}

上面的函數用來檢查文件是否存在,使用了boost::filesystem::is_regular_file。當path指向一個“常規(guī)文件”的時候,認為該文件存在;否則其它任何情況都認為文件不存在。

對于只有常規(guī)文件的情況,該函數沒有問題。但是,如果還存在其他文件時,如符號鏈接文件時,則返回文件不存在。

事實上,用boost::filesystem::status獲取時,會返回symlink_file,boost.filesystem將它們視為符號鏈接文件。

不論是常規(guī)文件還是符號鏈接文件,呈現給用戶的都是能夠正常使用的文件。

所以,不能單純地用boost::filesystem::is_regular_file來檢查文件是否存在了,下面是包裝函數的改進版本:

bool IsFileExistent(const boost::filesystem::path& path) {

    boost::system:error_code error;
    auto file_status = boost::filesystem::status(path, error);
    if (error) {
        return false;
    }

    if (! boost::filesystem::exists(file_status)) {
        return false;
    }

    if (boost::filesystem::is_directory(file_status)) {
        return false;
    }

    return true;
}

首先,通過boost::filesystem::status獲取文件的信息,如果發(fā)生錯誤,則認為文件不存在。

然后,使用boost::filesystem::exists判斷文件是否存在,該函數不區(qū)分文件夾和文件,所以最后還要使用boost::filesystem::is_directory判斷一下是否文件夾,只要不是文件夾,都認為文件是存在的。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容