Read File Into String in C++

  1. Use istreambuf_iterator to Read File Into String in C++
  2. Use rdbuf to Read File Into String in C++
  3. Use fread to Read File Into String
  4. Use read to Read File Into String

This article will explain several methods of reading the file content into a std::string in C++.

Use istreambuf_iterator to Read File Into String in C++

istreambuf_iterator is an input iterator that reads successive characters from the std::basic_streambuf object. Thus we can utilize istreambuf_iterator with an ifstream stream and read the whole contents of the file into a std::string.

At first, we open a given file path as an ifstream object. Then we can pass istreambuf_iterator<char>(input_file) to the string constructor and get the object we needed in the first place. Note that we are directly passing the string constructor statement to return from the function. The program’s output should be the contents of the file as specified by the filename variable.

#include <iostream>
#include <fstream>
#include <sstream>

using std::cout; using std::cerr;
using std::endl; using std::string;
using std::ifstream; using std::ostringstream;

string readFileIntoString(const string& path) {
    ifstream input_file(path);
    if (!input_file.is_open()) {
        cerr << "Could not open the file - '"
             << path << "'" << endl;
        exit(EXIT_FAILURE);
    }
    return string((std::istreambuf_iterator<char>(input_file)), std::istreambuf_iterator<char>());
}

int main()
{
    string filename("input.txt");
    string file_contents;

    file_contents = readFileIntoString(filename);
    cout << file_contents << endl;

    exit(EXIT_SUCCESS);
}

Use rdbuf to Read File Into String in C++

The rdbuf function is a built-in method to return a pointer to the stream buffer of the file, which is useful to insert the entire contents of the file using the << operator to the needed object.

In the following example, we construct an ostringstream object where we insert the rdbuf function’s return value. The function itself returns the string object, so the str method is used to get the final return value.

#include <iostream>
#include <fstream>
#include <sstream>

using std::cout; using std::cerr;
using std::endl; using std::string;
using std::ifstream; using std::ostringstream;

string readFileIntoString2(const string& path) {
    auto ss = ostringstream{};
    ifstream input_file(path);
    if (!input_file.is_open()) {
        cerr << "Could not open the file - '"
             << path << "'" << endl;
        exit(EXIT_FAILURE);
    }
    ss << input_file.rdbuf();
    return ss.str();
}

int main()
{
    string filename("input.txt");
    string file_contents;

    file_contents = readFileIntoString2(filename);
    cout << file_contents << endl;

    exit(EXIT_SUCCESS);
}

Use fread to Read File Into String

Another method for reading a file is the C standard library function fread. This method requires relatively legacy functions that are not common in the modern C++ codebases, but it offers significant speedup performance compared with the previous methods.

fread takes four arguments:

  1. A pointer to the buffer where read data is stored.
  2. The size of the data item.
  3. Number of data items
  4. The file pointer from which to read.

Since we are reading the whole file, the file size needs to be retrieved, and it’s implemented with the stat Unix system call. Once the file size is retrieved, we pass its value as the size of the data element to the fread function, and as the number of data items, we specify 1.

Note that opened files need to be closed with the fclose function call, which takes the only argument of the file pointer.

#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

using std::cout; using std::cerr;
using std::endl; using std::string;

string readFileIntoString3(const string& path) {
    struct stat sb{};
    string res;

    FILE* input_file = fopen(path.c_str(), "r");
    if (input_file == nullptr) {
        perror("fopen");
    }

    stat(path.c_str(), &sb);
    res.resize(sb.st_size);
    fread(const_cast<char*>(res.data()), sb.st_size, 1, input_file);
    fclose(input_file);

    return res;
}

int main()
{
    string filename("input.txt");
    string file_contents;

    file_contents = readFileIntoString3(filename);
    cout << file_contents << endl;

    exit(EXIT_SUCCESS);
}

Use read to Read File Into String

The read method is POSIX compliant function call available on various operating systems and can be the most flexible one if the programmer knows to employ it efficiently. fread itself calls read underneath, but this doesn’t guarantee the faster operation in all cases, as multiple factors play a hand in the efficient use of such system calls.

The main difference with fread is that read needs a file descriptor argument to point to the file from where to read data. File descriptors are special integers associated with the open file streams that the program might have during the execution. It can be acquired using the open function call and stored in int type. The other two arguments of the read function are the pointer to the buffer where the data will be stored and the number of bytes needed to be read, the latter of which is retrieved with the fstat function call. Note that we are using the string.data as the buffer to store read file contents.

#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

using std::cout; using std::cerr;
using std::endl; using std::string;

string readFileIntoString4(const string& path) {
    struct stat sb{};
    string res;

    int fd = open(path.c_str(), O_RDONLY);
    if (fd < 0) {
        perror("open\n");
    }

    fstat(fd, &sb);
    res.resize(sb.st_size);
    read(fd, (char*)(res.data()), sb.st_size);
    close(fd);

    return res;
}

int main()
{
    string filename("input.txt");
    string file_contents;

    file_contents = readFileIntoString4(filename);
    cout << file_contents << endl;

    exit(EXIT_SUCCESS);
}

Related Article - C++ File

  • Check if a File Exists in C++
  • Read a File Line by Line in C++