Supposed I have a file called myfile.txt, its content is below:
I would like to open it, go to the "keyword", modify the string "mykeyword" to "changedkeyword" then save the file. Note that I want to save the change to the file, not to create another file. What should I do?
Now I know many of you will suggest me reading I/O classes. I know I/O classes but still couldn't find what I want. A simple source code would be great.
1) Read the entire file into memory, close the file stream. Modify the in-memory string. Open the file and write it back.
2) For each line in the file, read it and replace any words, writing each line to a new file. Close both files. Delete the first, rename the second to the first.
I know both these solutions. However, I'm looking for an efficient one as I need to do this many times in my program. And I think these solutions could be optimized much. Both your solution need to erase the whole file while all I need is modify one keyword. Immagine you have a big file but you only need to modify a words of 6 to 7 characters.
Okay then. If the word is the exact same size, then simply locate it and write the new word. Thats one optimization.
Another is to read until you find the word. Then read a buffer of size n+(replacement.length-original.length). Write the replaced word, then the buffer and continue until done.
How big are your files and how many of them and how timely do you have to be in this operation?