-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilehandle2.cpp
More file actions
90 lines (70 loc) · 1.86 KB
/
filehandle2.cpp
File metadata and controls
90 lines (70 loc) · 1.86 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <iostream>
#include <fstream>
using namespace std;
/*
// Function to write multiple lines to file
void writeToFile(string filename, bool overwrite) {
ofstream outfile;
if (overwrite) {
outfile.open(filename.c_str()); // Overwrite mode (default is trunc)
} else {
outfile.open(filename.c_str(), ios::app); // Append mode
}
if (!outfile) {
cout << "Error opening file!" << endl;
return;
}
cout << "Enter lines to write to the file (type 'END' on a new line to stop):\n";
string line;
cin.ignore(); // Clear input buffer
while (true) {
getline(cin, line);
if (line == "END") break;
outfile << line << endl;
}
outfile.close();
cout << "Writing completed successfully.\n";
}
*/
void writeToFile(string filename, bool overwrite){
ofstream outfile;
if(overwrite){
outfile.open(filename.c_str());
}else{
outfile.open(filename.c_str(),ios::app);
}
cout<<"Enter lines to insert (END to stop)"<<endl;
string line;
cin.ignore();
while(true){
getline(cin,line);
if(line == "END") break;
outfile<<line<<endl;
}
}
// Function to display file content
void readFromFile(string filename) {
ifstream infile(filename.c_str());
if (!infile) {
cout << "Error opening file for reading!" << endl;
return;
}
string line;
cout << "\nCurrent content of the file:\n";
while (getline(infile, line)) {
cout << line << endl;
}
infile.close();
}
int main() {
string filename;
char choice;
cout << "Enter file name: ";
cin >> filename;
cout << "Do you want to overwrite the file? (y/n): ";
cin >> choice;
bool overwrite = (choice == 'y' || choice == 'Y');
writeToFile(filename, overwrite);
readFromFile(filename);
return 0;
}