C/C++获取文件大小(转)

本文介绍了多种获取文件大小的方法,包括使用C++标准库中的文件流、C语言标准库函数、特定平台API(如Windows下的GetFileSize)、MFC及通过文件属性获取文件大小等。这些方法适用于不同的编程环境和需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值