C++ read the whole file in buffer

C++Raii

C++ Problem Overview


What is a good approach to read the whole file content in a buffer for C++?

While in plain C I could use fopen(), fseek(), fread() function combination and read the whole file to a buffer, is it still a good idea to use the same for C++? If yes, then how could I use RAII approach while opening, allocating memory for buffer, reading and reading file content to buffer.

Should I create some wrapper class for the buffer, which deallocates memory (allocated for buffer) in it's destructor, and the same wrapper for file handling?

C++ Solutions


Solution 1 - C++

There's no need for wrapper classes for very basic functionality:

std::ifstream file("myfile", std::ios::binary | std::ios::ate);
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);

std::vector<char> buffer(size);
if (file.read(buffer.data(), size))
{
    /* worked! */
}

Solution 2 - C++

You can access the contents of a file with a input file stream std::ifstream, then you can use std::istreambuf_iterator to iterate over the contents of the ifstream,

std::string
getFileContent(const std::string& path)
{
  std::ifstream file(path);
  std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());

  return content;
}

In this case im using the iterator to build a new string using the contents of the ifstream, the std::istreambuf_iterator<char>(file) creates an iterator to the begining of the ifstream, and std::istreambuf_iterator<char>() is a default-constructed iterator that indicate the special state "end-of-stream" which you will get when the first iterator reach the end of the contents.

Solution 3 - C++

Something I have in most of my programs:

/** Read file into string. */
inline std::string slurp (const std::string& path) {
  std::ostringstream buf; 
  std::ifstream input (path.c_str()); 
  buf << input.rdbuf(); 
  return buf.str();
}

Can be placed in a header.
I think I have found it here: https://stackoverflow.com/a/116220/257568

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvardView Question on Stackoverflow
Solution 1 - C++jrokView Answer on Stackoverflow
Solution 2 - C++AngelCastilloView Answer on Stackoverflow
Solution 3 - C++ArtemGrView Answer on Stackoverflow