-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path54filesi_o.cpp
More file actions
55 lines (43 loc) · 1.33 KB
/
Copy path54filesi_o.cpp
File metadata and controls
55 lines (43 loc) · 1.33 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
#include <iostream>
#include <fstream>
/*
CLASSES TO USE WITH FILES IN C++
1) fstreambase
2) ifstream --> derived from fstreambase
3) ofstream --> derived from fstreambase
*/
using namespace std;
/*
In order to work with files in c++, you will have to open it. Primarily, there are 2 ways to open a file :
1) Using constructors
2) Using the member function open() of the class
*/
int main()
{
// USING CONSTRUCTOR TO :
// Write to a file
string st1 = "This is a string";
ofstream out("file.txt"); // since this is writing to a file, if the file doesn't exists it creates it with the same name
// ^ ^ ^
// | | |
// class object file name as an argument to constructor
out << st1;
// The object name can be anything
out.close();
// Reading to a file
string st2;
ifstream in("file.txt");
in >> st2;
cout << st2;
// ofstream is used to write to file and ifstream is used to read the file
//When we use cout and in for reading the file into a string, it treats the blank space or new line as end
// for that to not happen, we use getline({{object}}, {{string}}) function
for (int i = 0; i < 2; i++)
{
getline(in, st2);
cout << st2<<endl;
}
// this reads the entire file.txt with spaces and new lines
in.close();
return 0;
}