-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileIO.cpp
executable file
·124 lines (111 loc) · 3.11 KB
/
FileIO.cpp
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
template <typename T>
void printVector(T dataVecs)
{
cout << endl;
// VERY IMP
//for (auto data : dataVecs)
//for(size_t i = 0; i < dataVecs.size(); i++)
for(vector<string>::size_type i = 0; i < dataVecs.size(); i++)
{
//cout << data << endl;
cout << dataVecs[i] << endl;
}
cout << endl;
cout << endl;
}
int main()
{
vector <string> fileLines;
string line;
ifstream ifile;
ofstream ofile;
// Read data from a file
{
ifile.open("samp.txt");
if (ifile.is_open())
{
while (!ifile.eof())
{
getline(ifile, line);
fileLines.push_back(line);
}
// As we have reached the EOF, time to close the file
ifile.close();
}
else
{
cout << "Unable to open the file" << endl;
}
printVector(fileLines);
}
// Write data to a new file
{
ofile.open("sampNew.txt");
if (ofile.is_open())
{
// Write all vector lines to the file
for (auto line : fileLines)
{
ofile << line << "\n";
}
// As we are done writing, close the file
ofile.close();
}
else
{
cout << "Unable to open the file" << endl;
}
}
// Print only comments, Print Comments lines
{
bool comment = false;
for (auto line : fileLines)
{
size_t slashPos = line.find("//");
size_t asterPos = line.find("/*");
size_t closePos = line.find("*/");
// VERY IMP: This should be done at the very beginning. Else this will never become false
if (closePos != string::npos)
{
comment = false;
}
// If this line is not a part of multi-line comment AND
// does not have any comments in it, then ignore the line)
if (!comment &&
slashPos == string::npos &&
asterPos == string::npos &&
closePos == string::npos)
{
continue;
}
// If the line is a part of multiline comment, print the line
if (comment)
{
cout << line << endl;
}
// If line has "//" find its postion and print till end
else if (slashPos != string::npos)
{
cout << line.substr(slashPos) << endl;
}
// If line has "/*" find its postion and print till end
else if (asterPos != string::npos)
{
comment = true;
cout << line.substr(asterPos) << endl;
}
// If line has "*/" find its postion and print till "*/"
else if (closePos != string::npos)
{
cout << line.substr(0, closePos) << endl;
}
}
}
cout << endl;
return 0;
}