How to Create, write and read a text file in C++ ?
To create, write and read a text file in C++, you can use the following methods:
Creating a Text File
To create a text file in C++, you can use the ofstream
class. Here's an example:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream file("example.txt");
if (file.is_open()) {
file << "This is a text file created using C++!";
file.close();
cout << "File created successfully.";
} else {
cout << "Error creating file.";
}
return 0;
}
In this example, we create a file named "example.txt" using the ofstream
class. We then check if the file is open using the is_open()
method. If the file is open, we write some text to it using the <<
operator and then close the file using the close()
method. If the file is not open, we print an error message.
Writing to a Text File
To write to a text file in C++, you can use the ofstream
class. Here's an example:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream file("example.txt", ios::app);
if (file.is_open()) {
file << "\nThis is some additional text added to the file.";
file.close();
cout << "Text added to file successfully.";
} else {
cout << "Error opening file.";
}
return 0;
}
In this example, we open the "example.txt" file in append mode using the ios::app
flag. We then check if the file is open using the is_open()
method. If the file is open, we write some additional text to it using the <<
operator and then close the file using the close()
method. If the file is not open, we print an error message.
Reading from a Text File
To read from a text file in C++, you can use the ifstream
class. Here's an example:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string line;
ifstream file("example.txt");
if (file.is_open()) {
while (getline(file, line)) {
cout << line << endl;
}
file.close();
} else {
cout << "Error opening file.";
}
return 0;
}
In this example, we open the "example.txt" file using the ifstream
class. We then check if the file is open using the is_open()
method. If the file is open, we read each line of the file using the getline()
method and print it to the console using the cout
statement. We then close the file using the close()
method. If the file is not open, we print an error message.