C++ How to Read Entire String From File
Read File Into String in C++
- Use
istreambuf_iterator
to Read File Into String in C++ - Utilize
rdbuf
to Read File Into String in C++ - Use
fread
to Read File Into String - Use
read
to Read File Into Cord
This commodity will explain several methods of reading the file content into a std::string
in C++.
Utilize istreambuf_iterator
to Read File Into Cord in C++
istreambuf_iterator
is an input iterator that reads successive characters from the std::basic_streambuf
object. Thus we can utilise 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 tin can pass istreambuf_iterator<char>(input_file)
to the string
constructor and go the object we needed in the start place. Note that we are directly passing the string
constructor statement to return from the function. The program'due south output should be the contents of the file every bit 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 the file - '" << path << "'" << endl; exit(EXIT_FAILURE); } return cord((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; leave(EXIT_SUCCESS); }
Use rdbuf
to Read File Into Cord in C++
The rdbuf
function is a built-in method to render 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 instance, we construct an ostringstream
object where nosotros insert the rdbuf
part's return value. The role itself returns the string
object, so the str
method is used to get the last 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; string readFileIntoString2(const cord& path) { auto ss = ostringstream{}; ifstream input_file(path); if (!input_file.is_open()) { cerr << "Could not open up the file - '" << path << "'" << endl; get out(EXIT_FAILURE); } ss << input_file.rdbuf(); render 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 mod C++ codebases, but information technology offers pregnant speedup performance compared with the previous methods.
fread
takes four arguments:
- A pointer to the buffer where read data is stored.
- The size of the information item.
- Number of data items
- 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 arrangement call. Once the file size is retrieved, nosotros pass its value equally the size of the data element to the fread
function, and as the number of data items, we specify i
.
Note that opened files demand to be closed with the fclose
function call, which takes the merely 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 principal() { cord filename("input.txt"); string file_contents; file_contents = readFileIntoString3(filename); cout << file_contents << endl; leave(EXIT_SUCCESS); }
Use read
to Read File Into String
The read
method is POSIX compliant role 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, every bit multiple factors play a manus in the efficient apply of such system calls.
The main difference with fread
is that read
needs a file descriptor statement to indicate 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 can be acquired using the open
function call and stored in int
blazon. The other two arguments of the read
office are the pointer to the buffer where the information will be stored and the number of bytes needed to be read, the latter of which is retrieved with the fstat
part call. Note that nosotros 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 cord& path) { struct stat sb{}; cord 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); shut(fd); return res; } int main() { string filename("input.txt"); string file_contents; file_contents = readFileIntoString4(filename); cout << file_contents << endl; leave(EXIT_SUCCESS); }
Write for usa
DelftStack manufactures are written by software geeks like you. If you lot too would similar to contribute to DelftStack by writing paid articles, you can check the write for us page.
Related Article - C++ File
kobayashientil1990.blogspot.com
Source: https://www.delftstack.com/howto/cpp/read-file-into-string-cpp/
0 Response to "C++ How to Read Entire String From File"
Post a Comment