How to Read String File in C++

Read File Into String in C++

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

This article volition 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 showtime, we open a given file path as an ifstream object. And so nosotros tin laissez passer 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 argument to return from the role. The programme's output should exist the contents of the file as specified past 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;  cord readFileIntoString(const string& path) {     ifstream input_file(path);     if (!input_file.is_open()) {         cerr << "Could not open up the file - '"              << path << "'" << endl;         exit(EXIT_FAILURE);     }     return string((std::istreambuf_iterator<char>(input_file)), std::istreambuf_iterator<char>()); }  int primary() {     string filename("input.txt");     cord file_contents;      file_contents = readFileIntoString(filename);     cout << file_contents << endl;      get out(EXIT_SUCCESS); }                          

Use rdbuf to Read File Into Cord in C++

The rdbuf part 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'south return value. The function itself returns the string object, so the str method is used to go the final render 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;  cord 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); }                          

Utilize fread to Read File Into String

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

fread takes four arguments:

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

Since nosotros are reading the whole file, the file size needs to be retrieved, and it's implemented with the stat Unix arrangement call. In one case the file size is retrieved, we pass its value as the size of the data chemical element to the fread function, and as the number of data items, we specify 1.

Note that opened files demand to exist 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{};     cord 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);      render res; }  int master() {     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 phone call available on various operating systems and tin 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, every bit multiple factors play a manus in the efficient apply of such system calls.

The main departure with fread is that read needs a file descriptor argument to betoken to the file from where to read data. File descriptors are special integers associated with the open up file streams that the program might accept during the execution. It tin can be caused using the open up part telephone 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 office call. Note that nosotros are using the string.data as the buffer to shop 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::cord;  cord readFileIntoString4(const string& path) {     struct stat sb{};     cord res;      int fd = open up(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);     shut(fd);      render res; }  int primary() {     string filename("input.txt");     cord file_contents;      file_contents = readFileIntoString4(filename);     cout << file_contents << endl;      exit(EXIT_SUCCESS); }                          

Write for us

DelftStack manufactures are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you tin check the write for united states of america page.

Related Article - C++ File

  • Read File Char by Char in C++
  • Become List of Files in Directory in C++
  • Ezoic

    trostpren1967.blogspot.com

    Source: https://www.delftstack.com/howto/cpp/read-file-into-string-cpp/

    Related Posts

    0 Response to "How to Read String File in C++"

    Post a Comment

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel