Menu

#1024 std::ifstream::read doesn't read >INT_MAX (2 GB)

v1.0 (example)
open
nobody
None
5
2026-05-06
2026-05-06
Piotr Fusik
No

https://en.cppreference.com/cpp/io/basic_istream/read accepts std::streamsize count which is 64-bit. However, when passed count > INT_MAX, it fails to read.

#include <fstream>
#include <iostream>

int main()
{
    std::ifstream s;
    s.open("multi-gigabyte-file", std::ios::in | std::ios::binary);
    size_t n = INT_MAX + size_t(1);
    char *a = new char[n];
    s.read(a, n);
    std::cout << s.gcount() << '/' << n << '\n';
}

prints:

0/2147483648

I'm reproducing this with:

g++ (Rev2, Built by MSYS2 project) 16.1.0
Copyright (C) 2026 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

MSVC works as expected.

I googled someone already experienced this issue back in 2019:

https://stackoverflow.com/questions/59035518/reading-large-binary-chunk-int32-max-with-stdifstreamread

Discussion


Log in to post a comment.

MongoDB Logo MongoDB