0

I want to remove some information from a text file without shifting its all records. For example a text file customers.txt is given. it have a lot of records seperated by # delimiter. and each record contains fields separated by ;. Like this: 1665;John;Smith given a customer id, I want to remove a customer with corresponding id. I can find offset and length of the record in the file, but don't know how to remove it. do i have to re-write whole file?

Note: I'm using Standard C++ with g++4.5 and libst4.

sorush-r
  • 10,490
  • 17
  • 89
  • 173
  • possible duplicate of [How to overwrite only part of a file in c++](http://stackoverflow.com/questions/2530274/how-to-overwrite-only-part-of-a-file-in-c) – Binary Worrier Mar 01 '11 at 14:42
  • @Simone: Oops. Haven't seen it. Removed the useless comment. Thanks. – ereOn Mar 01 '11 at 14:43

2 Answers2

7

You have a couple of choices. 1) rewrite the remainder of the file past the record you are removing. 2) replace the record with some indicator that it is removed and handle that in your parsing of the file (like replacing the entry being removed with # or some other special character).

Lou
  • 1,955
  • 14
  • 16
  • Ok. I will replace like that. (I just wondered if is there a way to split a file to some fragmentations, something like OS do....) – sorush-r Mar 01 '11 at 14:55
  • @sorush There is no native way to do this. That's not to say you can't write a library to do that if you wish. – Lou Mar 01 '11 at 16:02
2

Yes, you have to rewrite the whole file.

I'd suggest this algorithm:

  • create a temporary file;
  • for each record that's not going to be deleted, copy it in the temporary file;
  • swap the temporary file with the original file.
Simone
  • 11,655
  • 1
  • 30
  • 43