源碼下載:點擊下載
源碼如下:
#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檔案無法開啟,所以方法二、三無法擷取檔案大小,因此推薦使用方法一、四。
如果還有其它方法,請大家補充。
感謝賊寇在何方補充了第四種方法!