Click here to Skip to main content
15,890,825 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a text file: text1.txt
I have got a line number: $line_number

I want to delete all the lines before $line_number in that text file!

What I have tried:

My idea

//open file
//for loop line by line until $line_number
//in that loop delete line
//close file
Posted
Updated 17-May-22 3:57am
Comments
Richard MacCutchan 17-May-22 9:38am    
A better idea is to read this file until you get to the specific line number. Then for each remaining line that you read, write it to a new file. That way if you make any mistakes you will not have destroyed your original data.

1 solution

Basically, you can't. Text files don't have lines - they have line terminators which are just characters in a stream of characters which are interpreted by applications as an "end of line" marker. To delete a line from a file requires you to open a new file, copy all the lines up to the line to delete over, skip the line you want to delete, then copy the rest of the file over.
Then you can close both files, delete the input file, and rename the new file to the old file name. Or better, rename the original file to a backup, and then rename the new file to the old file name.

A very similar process is needed when you want to insert lines.

But if you want to delete or insert lines, the chances are you are using the wrong file type altogether, and should probably be using a database instead!
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900