C++ 判斷一個文件是否存在。存在則刪除

判斷一個文件是否存在

#include <sys/stat.h>
#include <string>
#include <fstream>
#pragma warning(disable:4996)

inline bool exists_test0(const std::string& name) {
    std::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_test3(const std::string& name) {
    struct stat buffer;
    return (stat(name.c_str(), &buffer) == 0);
}

int main() {
    std::string a = "savefile.txt";
    bool a1 = exists_test0(a);
    bool a2 = exists_test1(a);
    bool a3 = exists_test3(a);
    return 0;
}

stackoverflow上一大佬做了幾種方法的運行時間的實驗,在他的環境下,stat()函數的結果最優。

刪除文件

刪除文件的函數也有很多,
1.可以使用DeleteFile(str2); // 刪除文件
百度百科它的參數比較坑,MFC裏面的話,建議使用這個。
2.remove(a.c_str());remove()函數挺好的,適合在簡單的C++程序裏面使用。其參數類型是const char*.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章