21xrx.com
2024-09-17 03:44:30 Tuesday
登录
文章检索 我的文章 写文章
C++ ifstream.read无法读取2G大小文件的解决方法
2023-07-04 20:55:07 深夜i     --     --
C++ ifstream read 2G 解决方法

C++ 是一门广泛应用于编程语言,尤其在面向对象程序设计方面有广泛应用。在使用 C++ 编写文件阅读操作时,我们可能会遇到无法读取 2GB 大小文件的问题。这是由于 ifstream.read 函数的默认值为 int 类型,而 int 类型只能描述的最大数字为 2GB。但是,我们可以使用其他数据类型或自定义类型来解决这个问题。

一种解决方法是使用 std::streamsize 数据类型。std::streamsize 数据类型在不同操作系统上有不同的定义,但通常情况下,它被定义为 long long 或 long int。std::streamsize 能够描述大于 2GB 的数字,因此我们可以使用它来代替 int 类型。以下是使用 std::streamsize 来读取大文件的示例代码:


std::ifstream file("largefile.txt", std::ios::binary);

if (file.is_open()) {

  const std::streamsize bufferSize = 4096;

  char buffer[bufferSize];

  std::streamsize bytesRead = 0;

  while (file.read(buffer, bufferSize)) {

    std::streamsize count = file.gcount();

    bytesRead += count;

    // process buffer

  }

  if (file.eof()) // end of file reached

    std::cout << "Bytes read: " << bytesRead << std::endl;

   else if (file.fail()) // some other error

    std::cerr << "Error reading file." << std::endl;

  

  file.close();

}

以上代码中,我们使用了 std::streamsize 来定义缓冲区大小和每次读取的字节数。我们可以根据需要更改这些值。在 while 循环中,我们使用 file.read 函数读取文件内容,并使用 file.gcount 函数获取实际读取的字节数。在循环结束后,我们可以使用 bytesRead 变量来获取读取的总字节数。

除了使用 std::streamsize,我们也可以自定义一个数据类型来解决这个问题。例如,我们可以定义一个名为 uint64_t 的类型,它的范围是 0 到 18,446,744,073,709,551,615(即 2^64-1)。以下是使用 uint64_t 类型来读取大文件的示例代码:


typedef uint64_t file_size_t;

const file_size_t bufferSize = 4096;

const file_size_t twoGB = 2147483648;

std::ifstream file("largefile.txt", std::ios::binary);

if (file.is_open()) {

  char buffer[bufferSize];

  file_size_t bytesRead = 0;

  while (file.read(buffer, bufferSize)) {

    file_size_t count = file.gcount();

    bytesRead += count;

    if (bytesRead > twoGB)

      // the file is too large

      break;

    

    // process buffer

  }

  if (file.eof()) // end of file reached

    std::cout << "Bytes read: " << bytesRead << std::endl;

   else if (file.fail()) // some other error

    std::cerr << "Error reading file." << std::endl;

  

  file.close();

}

以上代码中,我们使用 typedef 来定义一个名为 file_size_t 的类型,它被定义为 uint64_t。我们还定义了一个名为 twoGB 的常量,它的值为 2GB。在 while 循环中,如果 bytesRead 变量超过了 twoGB 的值,我们将跳出循环,以避免读取过大的文件。

总之,无法读取 2GB 大小的文件是一个常见的问题,但我们可以使用 std::streamsize 类型或自定义类型来解决它。通过适当的手动控制,我们可以在 C++ 中读取大文件并成功处理它们。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章