-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path55write_closefile.cpp
More file actions
65 lines (55 loc) · 2.15 KB
/
Copy path55write_closefile.cpp
File metadata and controls
65 lines (55 loc) · 2.15 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
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;
int main()
{
ofstream write("testfile.txt"); // this is an output stream where data will flow from code to file
// creating a name string and filling it with the string entered by the user
string name;
cout << "Enter your name : " << endl;
cin >> name;
// writing a string to the file
write << "My name is " + name; // + or << can be used
write.close();
// this off streams the file with the code or program and no operations or changes or activities can be made to or with the file
// reading from a file
ifstream read("testfile.txt");
// creating a string to store data from the file
string copy;
getline(read, copy); // this helps to read the entire line, cin or cout treats blank space as termination of string
cout << "The content of the file : " << copy << endl;
read.close();
// OPENING A FILE USING open() MEMBER FUNCTION OF FSTREAMBASE
ofstream tofile;
tofile.open("file.txt");
tofile << "This is a file in progress " << endl;
tofile << "File is unfinished\n"; // \n can be used for new line
tofile << "May give error " << endl;
tofile.close();
ifstream fromfile;
fromfile.open("file.txt");
string s1, s2;
// fromfile >> s1 >> s2; // taking string from the file into the program's string
// cout << s1 << s2 << endl;
/*for (int i = 0; i < 10; i++) // loop can read all the strings separated by blank space using cout
{
fromfile >> s2;
cout << s2 << endl;
}*/
// Better way to use loop to read all the content from a file
string s3;
while (fromfile.eof() == 0)
{
getline(fromfile, s3);
cout << s3 << endl;
}
/*
USING OF END OF FILE FUNCTION eof() MEMBER FUNCTION OF THE FSTREAMBASE
This function indicates the end of the file and can be used to read the entire file with while loop
access the function using ifstream object with dot operator '.'
If the eof() == 0, it means the file hasn't reached the end
If eof() == 1, it means we have reached the end of the file
*/
return 0;
}