Remove bytes from a file - c

MathMe picture MathMe · Oct 31, 2013 · Viewed 7.4k times · Source

How can I remove from a file, bytes from i to i.

Example: "today me and my roomates went to a party"; if i = 3, I want to remove the 3rd byte, the 6th, the 9th... etc I tried using lseek and fgets but I didn't know how to do the whole thing.

What I tried:

FILE* f = fopen(name_file,"r");
lseek(f,0,SEEK_SET);
while(fgets(lune,255,f) != NULL){
     lseek(f,i,SEEK_SET);
}

I didn't do too much because I don't know exactly what to do. Maybe you can help me with some answers and tips.

Answer

Alexander L. Belikoff picture Alexander L. Belikoff · Oct 31, 2013

If by remove you mean physically removing bytes from the file's contents (in the middle of the file), you cannot do that. You have to open another file and selectively copy contents you want to keep into it. So the way to do it as as follows:

  • open() the source file for reading (I assume low-level I/O but stdlib f* functions would work similarly)
  • open() destination file for writing
  • lseek() to the correct location
  • read() the portion to keep
  • write() to the destination file
  • repeat the last 3 operations until done.

Note that you are calling lseek() on FILE* which is not the right way (check your compiler warnings. You should be using fseek()

Yet another way would be to mmap() the file and read portions of it as if it was an array.

Finally, if your file is a simple string, the simplest way might be to read it in memory and copy the right pieces into the output file.