在一些实际的项目中,我们需要去计算某目录下的某个文件的大小,从而继续后续的业务;
如下的方法是各个平台通用的方法,简洁实用,已经验证和测试过:
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifdef WIN32
#include <windows.h>
#else
#include <unistd.h>
#include <sys/syscall.h>
#ifdef APPLE
#include <sys/mount.h>
#else
#include <sys/statfs.h>
#endif //#ifdef APPLE
#endif //#ifdef WIN32
int64_t GetFileSize(const char * lpFileUrl)
{
struct stat fileStat;
if (stat(lpFileUrl, &fileStat) < 0)
{
return 0;
}
else
{
return fileStat.st_size;
}
}