先用fopen打開檔案,然後把檔案指針指向檔案尾.
再用ftell獲得檔案指針目前位置(即檔案長度).
源代碼:
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
file* fp = null;
int nfilelen = 0;
fp = fopen("c:/test.txt", "rb");
if (fp == null)
cout << "can't open file" << endl;
return 0;
}
fseek(fp,0,seek_end); //定位到檔案末
nfilelen = ftell(fp); //檔案長度
cout << "file len = " << nfilelen << endl;
可以用 stat (win 下 _stat)函數直接得檔案尺寸。
man 2 stat
1.mfc中的方法:(c++)
cfilestatus status;
cfile::getstatus("d:\\test.txt",status);
long lsizeoffile;
lsizeoffile = status.m_size;
lsizeoffile的值就是d:\\test.txt檔案的大小
2.标準c獲得檔案大小的5種方法
(注意:"__file__"指的是目前檔案,你可以改為有效路徑的目标檔案,比如"d:\\test.txt")
struct stat {
dev_t st_dev; /* id of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user id of owner */
gid_t st_gid; /* group id of owner */
dev_t st_rdev; /* device id (if special file) */
off_t st_size; /* total size, in bytes */
blksize_t st_blksize; /* blocksize for filesystem i/o */
blkcnt_t st_blocks; /* number of blocks allocated */
time_t st_atime; /* time of last access */
time_t st_mtime; /* time of last modification */
time_t st_ctime; /* time of last status change */
#include "stdio.h"
#include <sys/stat.h>
#include <io.h>
#include <fcntl.h>
int getfilesize()
int iresult;
struct _stat buf;
iresult = _stat(__file__,&buf);
if(iresult == 0)
return buf.st_size;
return null;
int getfilesize01()
int fp;
fp=_open(__file__,_o_rdonly);
if(fp==-1)
return _filelength(fp);
//return null;
int getfilesize02()
return _lseek(fp,0,seek_end);
int getfilesize03()
int getfilesize04()
file *fp;
if((fp=fopen(__file__,"r"))==null)
fseek(fp,0,seek_end);
return ftell(fp); //return null;
int getfilesize05()
char str[1];
if((fp=fopen(__file__,"rb"))==null)
for(int i = 0;!feof(fp);i++)
fread(&str,1,1,fp);
return i - 1; //return null;
int main(int argc, char* argv[])
printf("getfilesize()=%d\n",getfilesize());
printf("getfilesize01()=%d\n",getfilesize01());
printf("getfilesize02()=%d\n",getfilesize02());
printf("getfilesize03()=%d\n",getfilesize03());
printf("getfilesize04()=%d\n",getfilesize04());
printf("getfilesize05()=%d\n",getfilesize05());