1. 程式人生 > >C++的6種獲取檔案大小的方法

C++的6種獲取檔案大小的方法

long getFileSize1(const char* strFileName)
{
    FILE * fp = fopen(strFileName, "r");
    fseek(fp, 0L, SEEK_END);
    long size = ftell(fp);
    fclose(fp);
    return size;
}

long getFileSize2(const char* strFileName)
{
    struct _stat info;
    _stat(strFileName, &info);
    long size = info.st_size;
    return
 size;
}

long getFileSize3(const char* strFileName)
{
    FILE* file = fopen(strFileName, "rb");
    if (file)
    {
        long size = filelength(fileno(file));
        fclose(file);
        return size;
    }
    return 0;
}

ULONGLONG getFileSize4(const char* strFileName)
{
    CFile cfile;
    if (cfile.Open(strFileName, CFile::modeRead))
    {
        ULONGLONG size = cfile.GetLength();
        return
 size;
    }
    return 0;
}

long getFileSize5(const char* strFileName)
{
    HANDLE handle = ::CreateFile(strFileName, FILE_READ_EA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
    if (handle != INVALID_HANDLE_VALUE)
    {
        long size = ::GetFileSize(handle, NULL);
        ::CloseHandle(handle);
        return
 size;
    }
    return 0;
}

long getFileSize6(const char* strFileName)
{
    std::ifstream in(strFileName);
    if (!in.is_open()) return 0;

    in.seekg(0, std::ios_base::end);
    std::streampos sp = in.tellg();
    return sp;
}