21xrx.com
2025-03-31 19:07:38 Monday
文章检索 我的文章 写文章
如何用C++获取文件大小?
2023-07-13 02:03:34 深夜i     39     0
C++ 获取 文件 大小

在 C++ 中获取文件大小是一个非常基础的操作,可以用来判断文件是否为零或读取文件的大小限制。在本文中,我们将介绍几种方法来获取 C++ 中的文件大小。

方法1:使用 std :: ifstream 类

这是一种最基本的方法。我们可以使用 std :: ifstream 类打开文件并获取文件大小。代码示例如下:

#include <iostream>
#include <fstream> // 包含 ifstream
using namespace std;
int main() {
  // 打开文件
  ifstream myfile("example.txt");
  // 获取文件大小
  myfile.seekg(0, ios::end);
  int size = myfile.tellg();
  // 关闭文件
  myfile.close();
  cout << "文件大小为 " << size << " 字节" << endl;
  
  return 0;
}

在上述代码中,使用 std :: ifstream 打开了文件 “example.txt”。使用 seekg 函数将文件指针移到文件结束处,使用 tellg 函数获取文件指针位置,从而得到文件的大小。

方法2:使用文件流(fstream)

可以使用文件流(fstream)来获取文件的大小,这种方法也比较基础,适用于较小的文件。代码示例如下:

#include <iostream>
#include <fstream>
using namespace std;
int main() {
  // 打开文件流
  fstream myfile("example.txt", ios::in | ios::binary);
  // 获取文件流大小
  myfile.seekg(0, ios::end);
  int size = myfile.tellg();
  // 关闭文件流
  myfile.close();
  cout << "文件大小为 " << size << " 字节" << endl;
  return 0;
}

在上述代码中,我们使用 fstream 打开了文件并使用 seekg 函数将文件指针移到文件结束处,使用 tellg 函数获取文件指针位置。最后,我们关闭了文件流并输出文件大小。

方法3:使用 boost 库

如果您使用 boost 库,则可以使用它的 boost :: filesystem :: file_size 函数来获取文件的大小。代码示例如下:

#include <iostream>
#include <boost/filesystem.hpp>
using namespace std;
int main() {
  // 获取文件大小
  int size = boost::filesystem::file_size("example.txt");
  cout << "文件大小为 " << size << " 字节" << endl;
  return 0;
}

在上述代码中,我们使用 boost :: filesystem :: file_size 函数获取文件 “example.txt” 的大小,并输出。

通过这些方法,您可以轻松地在 C++ 中获取文件的大小。根据您的实际需求选择其中一种方法进行操作即可。

  
  

评论区

请求出错了