![]() |
VOOZH | about |
In C++, file handling allows us to read and write data to an external file from our program. In this article, we will learn how to read a file into a string in C++.
To read an entire file line by line and save it into std::string, we can use std::ifstream class to create an input file stream for reading from the specified file with a combination of std::getline to extract the lines from the file content that can be concatenated and stored in a string variable.
- Open the file using std::ifstream file(filePath).
- Use the is_open() method to check if the file was opened successfully, if not print error message and return.
- Use a loop with std::getline(file, line) to read each line of the file into a string and print the populated string.
- Close the file stream.
The below program demonstrates how we can read the content of a file into a std::string line by line in C++.
Output
File Content: Hi, Geek! Welcome to gfg. Happy Coding ;)
Time Complexity: O(n), here n is total number of characters in the file.
Auxiliary Space: O(n)