C/C++多種方法擷取檔案大小

來源:互聯網
上載者:User

源碼下載:點擊下載

源碼如下:

 

#include <iostream>
#include <io.h>
#include <sys\stat.h>
#include <afx.h>
#define _AFXDLL
using namespace std;

void main()
{
    // 此檔案在工程開啟狀態下為不可訪問
    char* filepath = "..\\test.ncb";

    // 方法一
    struct _stat info;
    _stat(filepath, &info);
    int size = info.st_size;
    cout<<size<<endl;

    // 方法二
    FILE* file = fopen(filepath, "rb");
    if (file)
    {
        int size = filelength(fileno(file));
        cout<<size<<endl;
        fclose(file);
    }

    // 方法三
    CFile cfile;
    if (cfile.Open(filepath, CFile::modeRead))
    {
        int size = cfile.GetLength();
        cout<<size<<endl;
    }

    // 方法四
    HANDLE handle = CreateFile(filepath, FILE_READ_EA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
    if (handle != INVALID_HANDLE_VALUE)
    {
        int size = GetFileSize(handle, NULL);
        cout<<size<<endl;
        CloseHandle(handle);
    }
}

 

 

VS2005:若編譯連結不通過,需要修改工程設定:

(1) Configuration Properties -> C/C++ -> Code Generation -> Runtime Library, 選擇"Multi-threaded Debug(/MTd)"

(2) Configuration Properties -> Linker -> Input -> Ignore Specific Library, 輸入"msvcprtd.lib"

 

例子中,由於在工程開啟狀態下,test.ncb檔案無法開啟,所以方法二、三無法擷取檔案大小,因此推薦使用方法一、四。

如果還有其它方法,請大家補充。

感謝賊寇在何方補充了第四種方法!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.