jeudi 4 janvier 2018

tellg() returns -1 only for small files

I ran across a peculiar issue. Let's say I'm reading a file like this:

std::ifstream in("file.txt", std::ios::binary);
std::string text;
in.seekg(0, std::ios::end);
text.resize(in.tellg());
in.seekg(0, std::ios::beg);
in.read(&text[0], text.size());

The problem arises when the file contains less than 4 characters, i.e. "ab" or "abc", but works in other cases as intended, i.e. "abcd" or larger.

Why is tellg returning -1 for such a situation (ultimately causing my string to throw a std::length_error)?

Additional info:

I'm working with MSVC 15.5.3 (if not the latest, one of the more contemporary). Reproduced with GCC 5.1 as well.

This error doesn't occur with the equivalent C-style:

FILE* f = fopen("text.txt", "rb");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);

EDIT:

failbit is set right before the first call to seekg, meaning opening the file failed? Why would that be the case for a file of less than 3 bytes...

Aucun commentaire:

Enregistrer un commentaire