首页 > 其他分享 >cpp 获取文件是否存在 获取文件大小

cpp 获取文件是否存在 获取文件大小

时间:2022-10-18 17:24:33浏览次数:36  
标签:std 文件大小 stat return name int 获取 file cpp


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_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);
}
int fileSize(const char *add){
    std::ifstream mySource;
    mySource.open(add, std::ios_base::binary);
    mySource.seekg(0,std::ios_base::end);
    int size = mySource.tellg();
    mySource.close();
    return size;
}
int get_file_size(std::string filename) // path to file
{
    FILE *p_file = NULL;
    p_file = fopen(filename.c_str(),"rb");
    fseek(p_file,0,SEEK_END);
    int size = ftell(p_file);
    fclose(p_file);
    return size;
}
long GetFileSize(std::string filename)
{
    struct stat stat_buf;
    int rc = stat(filename.c_str(), &stat_buf);
    return rc == 0 ? stat_buf.st_size : -1;
}


long FdGetFileSize(int fd)
{
    struct stat stat_buf;
    int rc = fstat(fd, &stat_buf);
    return rc == 0 ? stat_buf.st_size : -1;
}

标签:std,文件大小,stat,return,name,int,获取,file,cpp
From: https://www.cnblogs.com/simp/p/16803309.html

相关文章