Search code examples
c++readfileeof

Reading empty file in C++ returns 255, 0 expected


When I run my code to read file it works in every way. Any ASCII code I find in file, can get printed using my function. But when it reaches EOF I would expect it to return 0, but it returns 255 instead. Why does that happen and how do I fix that.
Segment of my code:

uint8_t FileDevice::read () {
    ifile.open(this->fileName);
    if (!ifile) ifile.open(this->fileName.c_str(), ifstream::app);
    ifile.seekg(this->position);
    uint8_t character;
    character = ifile.get();
    ifile.close();
    this->position++;
    printf("%d\n", character);
    return character;
}

Solution

  • The possibility of returning EOF is the main reason istream::get does not return a char but a wider integer type.

    If EOF would be returned as 0 you would not be able to distingish it from a non-EOF 0.

    The value of EOF is part of the char traits of the stream. You can find it here std::char_traits<CharT>.

    As its all templates and no specific CharT refered to in documentation it can be cumbersome to wade through. This site as a very handy overview also listing most important features of the char_traits<char>: https://en.cppreference.com/w/cpp/string/char_traits.

    Last but not least, EOF is specified to be negative and once wrapped around you cannot tell the difference between a "good" value and the EOF. Hence you should not use uint8_t for the return value of get. Use the appropriate integer type and only after checking for EOF you can store it the target type.