How to Read Whole ASCII File Into C++ std::string?
An ASCII file is a text file that has a standardized format so that information can be recognized and read easily by any platform or operating system. In C++, we represent the textual data as std::string objects. In this article, we will learn how to read a whole ASCII File into std::string in C++.
Read Whole ASCII File into C++ std::string
To read an entire ASCII file and save it into std::string,
we can use the std::ifstream
class to open and read the file with a combination of std::istreambuf_iterator
to read the whole file content into a string.
Approach
- First, open the file using
std::ifstream file(filePath) that
creates an input file stream for reading from the specified file.- Next, check if the file was opened successfully using the is_open() method. If the opening fails, print an error and return from the function.
- Then, read the whole file into a string using
std::istreambuf_iterator<char>(file) that
creates an iterator to read characters fromfile
from the beginning of the file.- Finally, close the file stream and print the populated string.
C++ Program to Read the Content of ASCII File into std::string
The below example demonstrates how we can read the content of an ASCII File into a std::string in C++.
C++
// C++ Program to read whole ASCII file into C++ std::string #include <fstream> #include <iostream> #include <string> using namespace std; int main() { // Replace "example.txt" with the path to your actual // file string filePath = "ascFile.txt" ; // Open the file using ifstream ifstream file(filePath); // Check if the file was opened successfully if (!file.is_open()) { cerr << "Failed to open file: " << filePath << endl; return 1; // Exit with error code if the file cannot // be opened } // Read the whole file into a string string fileContent((istreambuf_iterator< char >(file)), istreambuf_iterator< char >()); // Close the file (optional here since the file will be // closed automatically when file goes out of scope) file.close(); // Output the file content to the console cout << "File content:\n" << fileContent << endl; return 0; } |
Output
File content:
"New England", "Massachusetts", "Boston", "SuperMart",
"Feb" , 2000000"New England", "Massachusetts", "Springfield", "SuperMart",
"Feb" , 1400000"New England", "Massachusetts", "Worcester", "SuperMart",
"Feb" , 2200000
Time Complexity: O(n), where n is the number of characters in the file.
Space Complexity: O(n)
Contact Us