-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMoreFileInOutDEMO.cpp
More file actions
87 lines (67 loc) · 2.31 KB
/
Copy pathMoreFileInOutDEMO.cpp
File metadata and controls
87 lines (67 loc) · 2.31 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
//************************************************************************
// Author: Rolando Carreon
// Date: apr 1 2025
// Language: C++
// Assignment: More File In Out DEMO
// Description: create a file, read the file, and read/write a file
//************************************************************************
#include<iostream>
#include<fstream>
#include <string>
using namespace std;
int main()
{
// declare local variables
ofstream myOutFile("example.txt");
//cehck if the file opens successfull
if ( myOutFile.is_open() )
{
// write to the file
myOutFile << "Hello World!\n";
myOutFile << "This is a C++ file writing example\n";
myOutFile.close(); // close the file
}
else
cout << "Unable to open the file for writing.\n";
//----------------------------
// declare local variables
fstream myInFile ("example.txt");
string line;
// check if the file opens successfully
if ( myInFile.is_open() )
{
// loop through the file reading/ displaying one line ar a time
// exits loop if failstate occurs like file never opened
while ( getline(myInFile, line) )
{
cout << line << "\n";
}
myInFile.close(); // close the file
}
else
cout << "Unable to open file for reading.\n";
//----------------------------------------------------
// declare local variables
// overloading - read in | write out, might need .append
fstream myFile("example.txt", ios::in | ios::out);
string line2;
// check if the file opened successfully
if (myFile.is_open())
{
// loop through the file reading/ displaying one line ar a time
// exits loop if failstate occurs like file never opened
while ( getline(myFile, line2) )
{
cout << line2 << "\n";
}
//clears failed states like the while loop
myFile.clear(); // clear any error flags
// seekp sets line to line0 and the ios beg sets to begging of line
myFile.seekp(0, ios::beg);
myFile << "New Content added.\n";
myFile.close();
}
else
cout << "Unable to open the file.\n";
return 0;
}