C++ Read in Words From Txt File Fstream

Read File Into String in C++

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

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 tin can utilize istreambuf_iterator with an ifstream stream and read the whole contents of the file into a std::string.

At first, we open up a given file path as an ifstream object. Then we can pass istreambuf_iterator<char>(input_file) to the cord constructor and get the object we needed in the outset place. Note that we are direct passing the cord constructor statement to return from the function. The program'southward output should be 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::cord; 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;         go out(EXIT_FAILURE);     }     render 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 Cord 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 unabridged contents of the file using the << operator to the needed object.

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

              #include <iostream> #include <fstream> #include <sstream>  using std::cout; using std::cerr; using std::endl; using std::cord; 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();     render ss.str(); }  int master() {     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 meaning 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 particular.
  3. Number of data items
  4. The file arrow 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 organization phone call. Once the file size is retrieved, we pass its value every bit the size of the data element to the fread function, and as the number of data items, we specify ane.

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;  cord 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.information()), sb.st_size, one, input_file);     fclose(input_file);      render res; }  int chief() {     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, 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 up file streams that the program might have during the execution. Information technology can exist acquired using the open up function phone call and stored in int type. The other ii arguments of the read function are the arrow 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 role phone call. Note that we are using the string.information 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;  cord readFileIntoString4(const string& path) {     struct stat sb{};     cord res;      int fd = open(path.c_str(), O_RDONLY);     if (fd < 0) {         perror("open\northward");     }      fstat(fd, &sb);     res.resize(sb.st_size);     read(fd, (char*)(res.data()), sb.st_size);     close(fd);      render res; }  int primary() {     string filename("input.txt");     string file_contents;      file_contents = readFileIntoString4(filename);     cout << file_contents << endl;      get out(EXIT_SUCCESS); }                          

Write for u.s.a.

DelftStack manufactures are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for the states folio.

Related Article - C++ File

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

    boyntonlinceigh.blogspot.com

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

    0 Response to "C++ Read in Words From Txt File Fstream"

    Post a Comment

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel