Program to delete a line given the line number from a file
Last Updated :
20 Feb, 2018
Given a file and a line number n, the task is to delete nth line from the given text file.
Suppose the initial content of myfile.txt is :
GeeksforGeeks
GeeksforGeeks IDE
GeeksforGeeks Practice
GeeksforGeeks Contribute
After Deletion of Line 2 the content would be :
GeeksforGeeks
GeeksforGeeks IDE
GeeksforGeeks Contribute
Approach :
1) Open the source file in input mode and read it character by character.
2) Open another file in output mode and place contents in the file character by character.
3) Rename the other file to the source file.
#include <bits/stdc++.h>
using namespace std;
void delete_line( const char *file_name, int n)
{
ifstream is(file_name);
ofstream ofs;
ofs.open( "temp.txt" , ofstream::out);
char c;
int line_no = 1;
while (is.get(c))
{
if (c == '\n' )
line_no++;
if (line_no != n)
ofs << c;
}
ofs.close();
is.close();
remove (file_name);
rename ( "temp.txt" , file_name);
}
int main()
{
int n = 3;
delete_line( "a.txt" , n);
return 0;
}
|
Note: Run this code offline IDE keep text file name
as "a.txt" in same folder
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...