Better way of reading a file.

Code1
1
2
3
4
5
6
7
8
9
10
11
12
std::string readContentsOfFile(std::string fileName) {
  std::ifstream file(fileName.c_str());

  if (file.good()) {
      std::stringstream buffer;
      buffer << file.rdbuf();
      file.close();

      return buffer.str();
  }
  throw std::runtime_exception("file not found");
}


Code2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
string readFile(char *filename)
{
    ifstream inputFile(filename) ;
    if(!inputFile)
    {
        cerr << "Error reading input file " << endl;
    }

    string dataFromFile ;
    while(inputFile)
    {
        getline(inputFile, dataFromFile);
    }
    return dataFromFile ;
}


Which of these is better and why ? Can I improve the better one ?
Any suggestions will be appreciated..thanks
It looks like number one is more effiecient however, code 2 is more stable since throw std can take up more memory when it throws an runtime exception i mean i cant really explain it lol personally im using a version of your code 2 if you look at my thread you'll see what I mean.
I suppose Code1 would be superior when you want the entire file in a string and Code2 would be superior when you only want the last line of a file.
I think I should use the first version as mostly I am interested in reading the whole file.
I expected more replies though.
Anyways , thanks @Hitesh and @cire
Topic archived. No new replies allowed.