2

I found the following code for reading whole file into a string. Unfortunately, I do no know how to properly check if whole file content has been loaded. There is is_open function, however it does not provide all information. Will be grateful for any help!

std::ifstream file(fileName);
std::string content = std::string((
  std::istreambuf_iterator<char>(file)),
  std::istreambuf_iterator<char>());
no one special
  • 1,608
  • 13
  • 32

2 Answers2

1

You are looking for the End Of File, or EOF flag.

End of file fliag

Gem Taylor
  • 5,381
  • 1
  • 9
  • 27
1

You can use the rdstate utilities to examine (and reset if needed) the state of the input file stream.

In your program this would for instance work as follows:

#include <iostream>
#include <fstream>
#include <string>

int main()
{
    std::ifstream file("sample.txt");
    std::string content = std::string((
            std::istreambuf_iterator<char>(file)),
            std::istreambuf_iterator<char>());

    std::cout << "Reading status: " << file.rdstate() << std::endl;

    if (file.rdstate())
        std::cout << "Reading the file failed" << std::endl;

    return 0;
}

The first output is for demonstration - file.rdstate will be 0 if everything went well. If something went wrong it's value will be a system dependent sum of the three flags that contributes to it. I recommend you read the cited reference.

The if statement is the actual check that you can use in your program. You can add an exception throw in there too, or even replace the if with an assert - both strategies in case you actually want the program to stop if reading file failed. When using assert you would replace the if with

assert(!file.rdstate());

and add the <cassert> header. Assert will throw and terminate your program if the file.rdstate() value is 0 (interpreted as false), since you want the opposite - there is a negation upfront.

You can easily test these concepts/idea simply by specifying a non-existent file name, but I also recommend you this post for more explanation and testing ideas that will clarify the concept.

atru
  • 4,699
  • 2
  • 18
  • 19