-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilehandle.cpp
More file actions
54 lines (42 loc) · 1.02 KB
/
filehandle.cpp
File metadata and controls
54 lines (42 loc) · 1.02 KB
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
#include <iostream>
#include <fstream>
using namespace std;
// Function to write text to file
void writeToFile(string filename) {
ofstream outfile;
outfile.open(filename.c_str());
if (!outfile) {
cout << "Error creating file!" << endl;
return;
}
string text;
cout << "Enter text to write into file: ";
cin.ignore(); // clear buffer
getline(cin, text);
outfile << text << endl;
outfile.close();
cout << "Text written to file successfully.\n";
}
// Function to read text from file
void readFromFile(string filename) {
ifstream infile;
infile.open(filename.c_str());
if (!infile) {
cout << "Error opening file!" << endl;
return;
}
string line;
cout << "\nReading from file:\n";
while (getline(infile, line)) {
cout << line << endl;
}
infile.close();
}
int main() {
string filename;
cout << "Enter file name: ";
cin >> filename;
writeToFile(filename);
readFromFile(filename);
return 0;
}