-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplace_specific_line_of_file.cpp
More file actions
61 lines (50 loc) · 1.22 KB
/
replace_specific_line_of_file.cpp
File metadata and controls
61 lines (50 loc) · 1.22 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
/* This project do a task to replace a specific line with the given text by user */
#include<bits/stdc++.h>
#include<string>
#include<fstream>
#include<vector>
using namespace std;
int main(){
string file_name;
string text;
int line_number;
cout<<"Enter the file name :: ";
getline(cin,file_name);
cout<<"Enter the text :: ";
getline(cin,text);
cout<<"Enter the line number to replace :: ";
cin>>line_number;
fstream in;
in.open(file_name);
if(in.fail()){
cout<<"SORRY!!! file does not exist"<<endl;
return 1;
}
vector <string> lines;
string line;
while(getline(in,line)){
lines.push_back(line);
}
if(lines.size()<line_number){
cout<<"file have total "<<lines.size()<<" lines\n"<<line_number<<" line is not present in it."<<endl;
return 1;
}
in.close();
ofstream out;
out.open(file_name);
if(out.fail()){
cout<<"SORRY!!! file does not exist"<<endl;
return 1;
}
--line_number;
for(int i = 0;i<lines.size();i++){
if(i != line_number){
out<<lines[i]<<endl;
}
else{
out<<text<<endl;
}
}
out.close();
return 0;
}