The best way to understand something practical like file input and output in C++ is through an example. Let's suppose we're creating an application for a financial firm. This requires heavy data analysis and involves reading and writing to files regularly. To simulate this scenario, we're writing some lines into a file and then reading it.
1#include <fstream>
2#include <iostream>
3using namespace std;
4
5int main() {
6 ofstream MyFile("testfile.txt");
7
8 // Check if the file is opened
9 if (MyFile.is_open()) {
10 MyFile << "This text is being written to testfile.txt\n";
11 MyFile << "This is another line in the file.";
12 MyFile.close();
13 } else {
14 cout << "File could not be opened.";
15 }
16 string line;
17 ifstream MyReadFile("testfile.txt");
18
19 // Read file line by line and print to console
20 while (getline (MyReadFile, line)) {
21 cout << line << '\n';
22 }
23 MyReadFile.close();
24 return 0;
25}
In the above code snippet, we first open a file called 'testfile.txt' for writing with the 'ofstream' object 'MyFile'. We then write some lines of text and close the file. Following this we open our 'testfile.txt' with 'ifstream' object 'MyReadFile' for reading, we then read each line until the end of the file. This is a very simplistic example, but in a real-world application like the one in our financial firm, we could be writing and reading millions of numbers for further data analysis.
This exercise should have you familiar with the basic operations of file input/output in C++. You may need more advanced techniques for larger data sets or more complex data structures, but the fundamental concepts remain the same.
xxxxxxxxxx
using namespace std;
int main() {
ofstream MyFile("testfile.txt");
// Check if the file is opened
if (MyFile.is_open()) {
MyFile << "This text is being written to testfile.txt\n";
MyFile << "This is another line in the file.";
MyFile.close();
} else {
cout << "File could not be opened.";
}
string line;
ifstream MyReadFile("testfile.txt");
// Read file line by line and print to console
while (getline (MyReadFile, line)) {
cout << line << '\n';
}
MyReadFile.close();
return 0;
}