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*.

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