Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there any basic way to delete something from opened file

Tags:

c

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)

like image 654
H2O Avatar asked Dec 19 '25 00:12

H2O


1 Answers

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.

like image 145
u0b34a0f6ae Avatar answered Dec 21 '25 15:12

u0b34a0f6ae