-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.cpp
65 lines (47 loc) · 1.37 KB
/
file.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main() {
// Writing to a file
ofstream outFile("example.txt");
if (!outFile) {
cerr << "Error opening file for writing." << endl;
return 1;
}
outFile << "Hello, this is a sample file.\n";
outFile << "Adding some more text to the file.\n";
outFile.close();
// Reading from a file
ifstream inFile("example.txt");
if (!inFile) {
cerr << "Error opening file for reading." << endl;
return 1;
}
cout << "Contents of the file:\n";
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
// Appending to a file
ofstream appendFile("example.txt", ios::app);
if (!appendFile) {
cerr << "Error opening file for appending." << endl;
return 1;
}
appendFile << "Appending more text to the file.\n";
appendFile.close();
// Displaying the updated contents of the file
ifstream updatedFile("example.txt");
if (!updatedFile) {
cerr << "Error opening file for reading." << endl;
return 1;
}
cout << "\nUpdated contents of the file:\n";
while (getline(updatedFile, line)) {
cout << line << endl;
}
updatedFile.close();
return 0;
}