I am a student currently doing a project that needs to add, edit, find, delete phrases and word from a .txt file. But i cant seem to figure out how to find, delete and edit a specific phrase from the .txt file with my program, can anyone help me?
How to look for a phrase from a .txt file?
How to overwrite a specific phrase in a .txt file?
How to delete a phrase or line from a .txt file?
If the file is small enough to fit in memory, you could just read it in and process it there, and foget about file handling utilities. You'd have to think about the data structures you might use that support your stated operations.
Yes, i was thinking about how to structure the data on the .txt file. But how can i find a specific word from the file?
Oh, by the way the project is not primarily about editing file, its about testing our skills in C programming, so i have to do up this console application to do these things.
For find a specific word you must check letters one by one if You will not put whole text in memory. If You will put whole text in memory than it depends on type in which you put the text.
Alright, i tried to use the code below, but it seems that i can only search the first line of the .txt file and that first line must not contain any spaces or else it will not find.
Am i missing something? What can i add to make it find the whole .txt file?
The function getline() only reads one line of the file, so you probably have to put it in an while loop. I would suggest:
1 2 3
while(!infile.eof()){
...
}
The operator >> only reads to the next whitespace. But i wouldn't do these operations on the file, but stick to operations with the string you have extracted. This page explains the usage of the function copy
I got the searching for phrase part already, thanks alot.
Now for the delete part, if i can find the phrase, how can i delete it from the .txt file? I have tried str.erase(), but it seems that it only delete what is on the string and not the .txt file.
If i were to read the whole .txt file into memory first, then rewrite the whole file without writing the line i want to delete, how should i go about doing it?