In this article, we will discuss how to read whole ASCII file into C++ std::string. Before going to its implementation, we must know about the ASCII file in C++.
What is the ASCII Files?
The ext files converted to ASCII format allow data to be imported into programs other than the source. Delimited formats and Fixed-width formats are the two most common formats. One of the delimited formats is a CSV (comma-separated value).
Use the std::ifstream class to access and read the file and the std::istreambuf_iterator to read all the contents of the file into a string, and we can read the entire ASCII file and store it in std::string.
Approach:
- If we use the std::ifstream file(filePath), open the file first that opens the file and generates the input file stream to read from the given file.
- Next, use the is_open method to check if the file opened successfully. Return from the function, if the opening fails, print an error.
- After that, use the std::istreambuf_iterator<char>(file) function to read the entire file into a string. It creates an iterator to read characters from the file from the beginning.
- Close the file stream and print the filled string.
Example 1:
Let us take an example to demonstrate how to read whole ASCII file in C++ .
Example
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
std::string read_file_into_string(const std::string& filename) {
std::ifstream file(filename);
if (!file.is_open()) {
std::cerr << "Error opening file: " << filename << std::endl;
return "";
}
std::stringbuf buf;
file.get(buf, '\0');
return buf.str();
}
int main() {
std::string filename = "example.txt";
std::string file_contents = read_file_into_string(filename);
if (!file_contents.empty()) {
std::cout << "File contents:" << std::endl;
std::cout << file_contents << std::endl;
}
return 0;
}
Output:
Example 2:
Example
// 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 a file goes out of scope)
file.close();
// Output the file content to the console
cout << "File content:\n" << fileContent << endl;
return 0;
}
Output: