Removing from file

Feb 18, 2009 at 5:58pm
Hi,

my goal is to remove some lines from a textfile. Is there a good way to do it without removing the file and creating a new one?
Feb 18, 2009 at 7:14pm
Nope. You'll need to load the file, edit it, and write it back.
Feb 18, 2009 at 8:23pm
Ok, but what happens with shrinking files? For example, i have got the text "This is a way to long line" in my file and i want to replace it by "A short line". So it writes the second text and leaves the rest unmodified. Something like: "A short liney to long line" (with the "y to long line" still from the text before). I don't want to fill the rest with whitespaces, but i have got no other idea.
Feb 18, 2009 at 10:19pm
Move to the position you want to modify with seekp and write from there
Feb 19, 2009 at 1:34am
When you're writing back, just open the file truncating it.
Feb 19, 2009 at 7:15pm
The typical way to handle such things is to follow this order:

1. Rename the original file to something temporary (such as "foo.txt" to "foo.txt.bak")

2. Create a new file named as the original

3. Open both files

4. Read the original file, modify, write the new file.

5. Close both files.

6. Delete the original file (optional)

Some steps may be combined.


On Linux (and with MinGW), there exists the trunctate() and ftrunctate() functions:
http://linux.die.net/man/2/truncate

On Windows, you can use the SetEndOfFile() function:
http://msdn.microsoft.com/en-us/library/aa365531(VS.85).aspx

All this is very OS-dependant though, especially if you are working with >2GB files.

If you know you are working with just a very small file, you can load it into a std::deque of strings, modify it in memory, then just rewrite the file.

Hope this helps.
Feb 19, 2009 at 8:49pm
Duoas, i did the 6 steps and it works all fine. Thanks a lot!

Thanks to all for the help!
Mar 5, 2009 at 3:59pm
I am a programmer-turned computer science teacher. May I suggest an alternative ?

Use a scripting langauge for something like this - biterscripting, perl, bash, any language. I wrote the following in biterscripting ( http://www.biterscripting.com for free download) . The same logic can be followed in any scripting language.

You said: You want to replace "This is a way too long line" with "A short line", and leave the rest modified in file X.txt .

HERE IS THE CODE

var str content ; cat "X.txt" > $content
sal "^This is way too long line^" "A short line" $content
echo $content > X.txt

DONE

The sal command is String ALterer. Similar other commands for inserting, appending, counting strings, lines, words, characters are very helpful.

Sen
Mar 5, 2009 at 7:04pm
Without C++ and on Linux/UNIX:
> sed 's/OLDSTRING/NEWSTRING/g' oldfile.txt > newfile.txt

One command; no scripting. I use this to refactor code!
Topic archived. No new replies allowed.