21xrx.com
2025-07-07 14:45:34 Monday
登录
文章检索 我的文章 写文章
C++ 如何获取文件大小
2023-06-28 12:07:41 深夜i     76     0
C++ 文件 大小 获取

在C++程序中,获取文件大小是一项常见的操作。不同的操作系统提供了不同的方法来获取文件大小。在Windows操作系统中,可以使用GetFileSize函数来获取文件的大小,而在Linux系统中可以使用stat系统调用来获取文件大小。以下介绍C++中如何获取文件大小的方法。

在Windows中使用GetFileSize函数获取文件大小:

#include <Windows.h>
#include <iostream>
using namespace std;
int main(){
  HANDLE hFile = CreateFile("example.txt", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
  if(hFile == INVALID_HANDLE_VALUE)
    cout << "cannot open file" << endl;
    return 1;
  
  DWORD dwSize = GetFileSize(hFile, NULL);
  cout << "the size of example.txt is " << dwSize << endl;
  CloseHandle(hFile);
  return 0;
}

首先,需要使用CreateFile函数打开文件,如果文件不能打开则需要返回错误。接下来,使用GetFileSize函数来获取文件的大小,并用cout输出其大小。最后,使用CloseHandle函数关闭文件句柄。

在Linux中使用stat系统调用获取文件大小:

#include <sys/stat.h>
#include <iostream>
using namespace std;
int main(){
  struct stat buf;
  if(stat("example.txt", &buf) == -1)
    cout << "cannot get file status" << endl;
    return 1;
  
  cout << "the size of example.txt is " << buf.st_size << endl;
  return 0;
}

我们可以使用stat系统调用来获取文件的信息,其中包括文件的大小。如果文件无法获取则需要返回错误。最后,输出文件的大小。

无论是在Windows还是Linux中,都可以通过以上方法来获取文件的大小。但是需要注意的是,文件大小为字节数,可以通过转换扩展为KB、MB等单位。同时,也需要注意文件路径的正确性,否则会造成文件打开失败或者获取文件大小失败。

  
  

评论区