tags:

views:

86

answers:

3

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)

+3  A: 

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.

kaizer.se
i think, this is not the easiest way but professional way...thanks for answer...
H2O
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 :-)
kaizer.se
Inshallah
+1  A: 

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  A: 

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