Repository navigation
Expand file tree
/
Copy pathq3.cpp
More file actions
63 lines (50 loc) · 1.53 KB
/
Copy pathq3.cpp
File metadata and controls
63 lines (50 loc) · 1.53 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
// WAP to user r/w file using fstream.
#include <iostream>
#include <fstream>
#include <string>
class FileHandler {
private:
std::fstream file; // File stream for both reading and writing
public:
// Member function to open a file in read/write mode
void openFile(const std::string& filename) {
file.open(filename, std::ios::in | std::ios::out | std::ios::app); // Open file in read/write mode, and append mode
if (!file) {
std::cerr << "Error opening file: " << filename << std::endl;
exit(1);
}
}
// Member function to write data to the file
void writeToFile(const std::string& data) {
file << data << std::endl;
}
// Member function to read data from the file
void readFromFile() {
std::string line;
while (getline(file, line)) {
std::cout << line << std::endl;
}
}
// Member function to reset the file pointer to the beginning
void resetFilePointer() {
file.seekg(0, std::ios::beg);
}
// Destructor to close the file
~FileHandler() {
if (file.is_open()) {
file.close();
}
}
};
int main() {
FileHandler fileHandler;
fileHandler.openFile("sample.txt");
// Writing to the file
fileHandler.writeToFile("Hello, World!");
// Reset file pointer to the beginning for reading
fileHandler.resetFilePointer();
// Reading from the file
std::cout << "Contents of the file:" << std::endl;
fileHandler.readFromFile();
return 0;
}