1.文件流
std::ifstream ifstr("filename");
ifstr.seekg( 0 , std::ios::end );
std::cout<<" file size:"<< ifstr.tellg()<<std::endl;
ifstr.seekg( ios::beg);
return 0;
2.C语言标准库函数fopen、fseek、ftell、fclose
FILE *fp;
if((fp=fopen("filename","r"))==NULL)
return 0;
fseek(fp,0,SEEK_END);
size = ftell(fp);
fseek(fp, 0.SEEK_SET)
fclose(fp);
或
FILE* file = fopen(filepath, "rb");
if (file)
{
int size = filelength(fileno(file));
cout<<size<<endl;
fclose(file);
}
3.特定平台的API,如Windows 下int size = GetFileSize(handle, NULL);其中handle是open或create一个文件以后获得
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);
}
4.MFC,本质是对第三种方法的封装,同样不具备跨平台性能
CFile cfile;
if (cfile.Open(filepath, CFile::modeRead))
{
int size = cfile.GetLength();
cout<<size<<endl;
}
或
CFileStatus status;
CFile::GetStatus("D://test.txt",status);
long lSizeOfFile;
lSizeOfFile = status.m_size;
5.文件属性方法:
struct _stat info;
_stat(filepath, &info);
int size = info.st_size;
cout<<size<<endl;