获取文件大小的六种方法大全,打开文件和不打开文件都有,C方法获取,C++方法获取,MFC方法获取。

来源:互联网 发布:js 数字转化为excel列 编辑:程序博客网 时间:2024/05/16 09:17
bool FileHelper::GetAFileSize(const char *path,unsigned __int64& fileSize){if(!IsFileExsist(path)){return 0;}//方案1,打开文件,获取文件大小    //HANDLE hFile = NULL;    //unsigned long size_low = 0, size_high = 0, bytes_read = 0;    //hFile = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ,    //    NULL, OPEN_EXISTING,0, NULL);    //if(hFile == INVALID_HANDLE_VALUE)    //{    //    return false;    //}    //size_low = GetFileSize(hFile, &size_high);    //SafeCloseFileHandle(hFile);    //fileSize = (unsigned __int64)size_low | (((unsigned __int64)size_high) << 32);//return true;//方案2,利用sys/stat.h中的stat结构体,不打开文件,获取到文件的大小//用到#include <sys/stat.h> //struct stat stat_buf; //if(stat(path, &stat_buf) < 0)//{//fileSize = 0;//return false;//}//fileSize = stat_buf.st_size;//return true; //方案3,利用WIN32_FIND_DATA结构体,不打开文件,获取到文件的大小WIN32_FIND_DATA ffd ;HANDLE hFind = FindFirstFile(path,&ffd);if(hFind != INVALID_HANDLE_VALUE){fileSize = (unsigned __int64)ffd.nFileSizeLow | (((unsigned __int64)ffd.nFileSizeHigh) << 32);
FindClose(hFind);//此处一定要记得关闭,不然文件一直会被占用。
return true;}return false;//方案4 用FILE//用到#include <io.h> FILE* file = fopen(path, "rb");  if (file)  {  fileSize = filelength(fileno(file));  fclose(file);  return true;}return false;////方案5,以下是MFC的方法//CFile cfile;  //if (cfile.Open(path, CFile::modeRead))  //{  //fileSize = cfile.GetLength();  //return true;//}//return false;////方案6,不用打开文件获取文件大小//CFile cfile;  //CFileStatus rStatus;//CFile::GetStatus(path,rStatus);//fileSize = rStatus.m_size;}

原创粉丝点击