Your problem is that you only write as many characters as you need for your replacement and leave the rest of the line (and the file) alone, thus anything that was longer than your replacement remains.
You have two options:
- if it's acceptable replace the rest of the line with spaces. You need to calculate the difference between the length of the original line and your replacement to know how many spaces to write.
- shift all the content after your replacement to remove the extra characters. You can only do that if you write to a different file though (maybe a temporary file that you then use to replace the original file).
A few other things:
- fseek(fid, 0, 'cof') does nothing. It says move 0 bytes from where you are now, that is don't move.
- You're not storing the whole file or any part of it in f{i}, just how many bytes you've written.