How to Read Whole ASCII File Into C++ std::string?
Last Updated :
22 Feb, 2024
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 from file
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++
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string filePath = "ascFile.txt" ;
ifstream file(filePath);
if (!file.is_open()) {
cerr << "Failed to open file: " << filePath << endl;
return 1;
}
string fileContent((istreambuf_iterator< char >(file)),
istreambuf_iterator< char >());
file.close();
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)
Share your thoughts in the comments
Please Login to comment...