Hi,
I want to be able to use std stream objects to manipulate files, but some of the files are too big. I want to be able to do the folowing:

>int64_t fileSize;
>strm.seekg(0,ios::end);
>fileSize = static_cast<int64_t>(strm.tellg());
>cout<<"File size is "<<fileSize;

This code will output -1 if the size of the file is too large to fit into an int type.

The reason I am type casting is that tellg() and other related stream functions return the streampos type. My problem is that the streampos type, which is equivalent to an int, is not big enough to contain the size of my file types. I need the int64_t for that.

thanks.

Dani AI

Generated

This thread raises the common portability issue that iostream position types are implementation-dependent. highlighted the symptom and noted some toolchains already accept larger seeks. For robust code, prefer APIs that explicitly expose 64-bit sizes instead of relying on streampos portability.

For modern C++ (C++17 and later) use std::filesystem::file_size, which returns a wide integer type and is a simple, portable way to get a file size (use the std::error_code overload to avoid exceptions):

#include <filesystem>
#include <system_error>

std::error_code ec;
auto size = std::filesystem::file_size("path/to/file", ec);
if (ec) { /* handle error */ }

If you must support pre-C++17 toolchains, use OS APIs: on POSIX call stat/fstat (ensure 64-bit off_t via _FILE_OFFSET_BITS=64 or the 64-bit variants), and on Windows use GetFileSizeEx or the CRT _fseeki64/_ftelli64 helpers. Also open streams in binary mode when comparing sizes, and always check stream error bits after seekg/tellg—a return of -1 can mean either a genuine overflow or a seek failure. Further reading: std::filesystem::file_size documentation (cppreference), POSIX stat (man7), and Windows GetFileSizeEx (Microsoft Docs).

Recommended Answers

All 2 Replies

Qucik correction, stream pos is equivalent to long, not int

Jon jon

It might be compiler dependent, but VC++ 2008 Express will accept a 64-bit integer as the first parameter to seekg() which I guess means it supports huge files.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.