Trevor Hickey
Trevor Hickey

Reputation: 37806

Remove A Line Of Text With Filestreams (C++)

I have a large text file.
Each time my program runs, it needs to read in the first line, remove it, and put that data back into the bottom of the file.

Is there a way to accomplish this task without having to read in every part of the file?
It would be great to follow this example of pseudo code:

1. Open file stream for reading/writing
2.   data = first line of file
3.   remove first line from file  <-- can I do this?
4. Close file stream

5. Open file stream for appending
6.   write data to file
7. Close file stream

The reason I'm trying to avoid reading everything in is because the program runs at a specific time each day. I don't want the delay to be longer each time the file gets bigger.

All the solutions I've found require that the program process the whole file. If C++ filestreams are not able to accomplish this, I'm up for whatever alternative is quick and efficient for my C++ program to execute.
thanks.

Upvotes: 3

Views: 1061

Answers (1)

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

The unfortunate truth is that no filesystem on a modern OS is designed to do this. The only way to remove something from the beginning of a file is to copy the contents to a new file, except for the first bit. There's simply no way to do precisely what you want to do.

But hopefully you can do a bit of redesign. Maybe each entry could be a record in a database -- then the reordering can be done very efficiently. Or perhaps the file could contain fixed-size records, and you could use a second file of indexes to specify record order, so that rearranging the file was just a matter of updating the indices.

Upvotes: 5

Related Questions