-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathseek.cpp
More file actions
67 lines (55 loc) · 1.73 KB
/
seek.cpp
File metadata and controls
67 lines (55 loc) · 1.73 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
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
fstream file;
string data;
// Step 1: Write data to file
file.open("sample.txt", ios::out); // open file for writing
if (!file) {
cout << "Error creating file!" << endl;
return 0;
}
file << "Hello, this is a C++ file handling demo.\n";
file << "File operations are fun to learn!";
file.close();
cout << "Data written successfully.\n";
// Step 2: Read and display data from file
file.open("sample.txt", ios::in);
if (!file) {
cout << "Error opening file for reading!" << endl;
return 0;
}
cout << "\n--- File Content ---\n";
while (getline(file, data))
cout << data << endl;
file.close();
// Step 3: Demonstrate seekg() - move read pointer
file.open("sample.txt", ios::in);
if (!file) {
cout << "Error opening file for seekg demo!" << endl;
return 0;
}
file.seekg(7, ios::beg); // Move read pointer to 7th byte from beginning
cout << "\nUsing seekg(7, ios::beg):\n";
while (getline(file, data))
cout << data << endl;
file.close();
// Step 4: Demonstrate seekp() - move write pointer and modify data
file.open("sample.txt", ios::in | ios::out);
if (!file) {
cout << "Error opening file for seekp demo!" << endl;
return 0;
}
file.seekp(0, ios::beg); // Move write pointer to beginning
file << "Hi"; // Modify first few characters
file.close();
// Step 5: Display modified content
file.open("sample.txt", ios::in);
cout << "\n--- Modified File Content ---\n";
while (getline(file, data))
cout << data << endl;
file.close();
return 0;
}