2

When you open a .txt file with fopen Is there any way to delete some strings in a file without rewriting.

For example this is the txt file that i will open with fopen() ;

-------------
1 some string
2 SOME string
3 some STRING
-------------

i want to delete the line which's first character is 2 and change it into

-------------
1 some string
3 some STRING
-------------

My solution is; First read all data and keep them in string variables. Then fopen the same file with w mode. And write the data again except line 2. (But this is not logical i am searching for an easier way in C ...) (i hope my english wasn't problem)

H2O
  • 582
  • 3
  • 12
  • Why do you say "this is not logical"? – William Pursell Aug 21 '09 at 13:28
  • i accept, "logical" was not the word that i mentioned. (this way is not easy to write. And i have concerns if there will be memory problems) I don't know how a txt file keeped in memory but if there is a way to delete some of data, like deleting an item from linked list, it will be much easier. (Not deleting but re-order of data) But probably i'll give up...(may be i am dreaming:) ) Thanks for interest... – H2O Aug 21 '09 at 13:57

3 Answers3

6

The easiest way might be to memory-map the whole file using mmap. With mmap you get access to the file as a long memory buffer that you can modify with changes being reflected on disk. Then you can find the offset of that line and move the whole tail of the file that many bytes back to overwrite the line.

u0b34a0f6ae
  • 48,117
  • 14
  • 92
  • 101
  • i think, this is not the easiest way but professional way... thanks for answer... – H2O Aug 21 '09 at 15:31
  • You are right, my answer may be seen as wrong, since mmap is not basic in the sense that you intended. Well if there is no other sensible way to solve this in-place, then the easiest way to solve a hard problem might still be tricky :-) – u0b34a0f6ae Aug 21 '09 at 16:09
  • 1
    @H2O, actually, I think this really is the easiest way: just map the file, search for the offset, and then memmove(&map[offset], offset + delete_length, file_size - offset - delete_length), DONE. – Inshallah Aug 21 '09 at 16:15
3

you should not overwrite the file, better is to open another (temp)-file, write contents inside and then delete old file and rename the file. So it is safer if problems occur. I think the easiest way is to

  1. read whole file
  2. modify contents in memory
  3. write back to a temp file
  4. delete original file
  5. rename temp file to original file

Sounds not too illogical to me..

Peter Parker
  • 29,093
  • 5
  • 52
  • 80
1

For sequential files, no matter what technique you use to delete line 2, you still have to write the file back to disk.

fpmurphy
  • 2,464
  • 1
  • 18
  • 22