Program to delete a line given the line number from a file

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.



filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to delete the given
// line number from a file
#include <bits/stdc++.h>
using namespace std;
  
// Delete n-th line from given file
void delete_line(const char *file_name, int n)
{
    // open file in read mode or in mode
    ifstream is(file_name);
  
    // open file in write mode or out mode
    ofstream ofs;
    ofs.open("temp.txt", ofstream::out);
  
    // loop getting single characters
    char c;
    int line_no = 1;
    while (is.get(c))
    {
        // if a newline character
        if (c == '\n')
        line_no++;
  
        // file content not to be deleted
        if (line_no != n)
            ofs << c;
    }
  
    // closing output file
    ofs.close();
  
    // closing input file
    is.close();
  
    // remove the original file
    remove(file_name);
  
    // rename the file
    rename("temp.txt", file_name);
}
  
// Driver code
int main()
{
    int n = 3;
    delete_line("a.txt", n);
    return 0;
}

chevron_right


 Note: Run this code offline IDE keep text file name 
as "a.txt" in same folder 


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.