0

how to delete a line from file

who can i find a string in file and delete the line witch that string is there?

16th Jan 2017, 2:51 PM
Matin Grimes
Matin Grimes - avatar
5 Answers
+ 11
@Luka // I have modified the code a tad. Please have a look. // tested on desktop compiler and is working fine. // I rearranged the scattered variable declarations and renamed several variables to make the program more descriptive. // Also, write-to-file (ofstream) functionalities have been modified into a function in order to avoid repetitive typing. #include <iostream> #include <cstdlib> #include <fstream> using namespace std; void deleteLine(string arr[], int target) { arr[target] = "---Deleted \n"; } void writeData(string arr[]) { ofstream outData; outData.open("Test.txt"); for (int i = 0; i < sizeof(arr); i++) { outData << arr[i]; } outData.close(); } int main() { string arr[] = {"first line \n", "second line \n", "and bla3 \n", "and bla bla4"}; string txt; int count = 0; int deletion_index; ifstream inData; writeData(arr); inData.open("Test.txt"); while (!(inData.eof())) { getline(inData, txt); cout << "line [" << count << "] = " << txt << endl; count++; } inData.close(); cout << "Please input index of desired line to be deleted." << endl; cin >> deletion_index; deleteLine(arr, deletion_index); writeData(arr); system("pause"); return 0; }
17th Jan 2017, 3:57 AM
Hatsy Rei
Hatsy Rei - avatar
+ 9
The method which first comes to mind would be to declare an array of string type and store the contents of the file line by line into the arrays. Then, we evaluate each line for the existing specific string, and get the index of the arrays which contains that string. Later during data writeback, skip the arrays with identified index. The lines will appear to be 'deleted' from the file.
16th Jan 2017, 4:03 PM
Hatsy Rei
Hatsy Rei - avatar
+ 8
@Luka No problem at all. :D
17th Jan 2017, 9:50 AM
Hatsy Rei
Hatsy Rei - avatar
+ 1
wait a minute.... who's Luka........?
17th Jan 2017, 11:40 AM
Leon lit
Leon lit - avatar
- 2
c5sasflr5llrw4sr5r45555fzg5wdf
16th Jan 2017, 11:11 PM
First Name
First Name - avatar