Remove the Last Line from a Text File in C++

In this tutorial, we will learn about how to Remove the Last Line from a Text File in C++.

Opening a File

fstream file;
file.open("abc.txt",ios::in);   //'in' is a type of file mode

Closing a File

file.close();

C++ program to remove the last line from a Text file

Let us write the code to illustrate the same. In this example, you can delete any line from the text file with the given C++ program.

I have written this code in an online IDE platform.

#include <bits/stdc++.h> 
using namespace std; 

void del_line(const char *file_name, int n)   
{ 	 
  ifstream fin(file_name);    

  ofstream fout;                
  fout.open("temp.txt", ios::out); 
  
  char ch; 
  int line = 1;            
  while(fin.get(ch)) 
  {      
    if(ch == '\n') 
      line++; 
     
    if(line != n)      // content not to be deleted 
      fout<<ch; 
  } 

  fout.close();  
  fin.close();   

  remove(file_name);        
  rename("temp.txt", file_name);  
} 

int main() 
{ 
  int n;
  cout<<"Enter the line number you want to delete: ";
  cin>>n;
  del_line("a.txt", n); 
  return 0; 
} 

Output:

Create a text file by the name “a.txt”.
Enter the data in it.

Text File (a.txt)

My name is xyz.
I am writing the code in C++.
I study in abcd College.
I live in Delhi.

Now, Input the line number

Enter the line number you want to delete: 4

After Deleting the line from a text file is:

My name is xyz.
I am writing the code in C++.
I study in abcd College.

Explanation:

In this code, first of all, the header file used contains all the standard header files in it. A function is defined to delete the last line having two arguments file name and line number. Then we create two text files one in reading mode and the other in write mode, we take the input character by character. We count the number of lines in the file. If the line number is not equal to the input number (n) that we want to delete, we copy the lines in the new text file. We don’t copy the line when line=n. Then remove the created file and rename the temporary file in it. Close the files.

Also, read: How to replace Particular Words in a Text File in Java

 

In the main() function we input the line number and call the del_line() function.

I hope this will help you to solve your problem.

Leave a Reply

Your email address will not be published. Required fields are marked *