Damiano Barbati
Damiano Barbati

Reputation: 3496

Rewrite lines on file

I need to rewrite a char on a file, or delete some lines. Is there a way to achieve this without rewriting the whole file?

Example: I need to change the char "8" at line 10 with char "4".

pollo
ciao fred
98/98/34 42ddw
4
10
1234567890
cristo
ciao liby
98/98/34 fre42ddw
8
20
12345678901234567890

Upvotes: 2

Views: 855

Answers (3)

Vlad
Vlad

Reputation: 35584

You can use fseek and fputc, if you know exactly the position of the char. If not, you should better first fread the file and find the needed position. For other utility functions, see <stdio.h>.

Note that <stdio.h> is byte-based, rather than line-based. With line-based methods you would basically need to rewrite the file.

For deleting line from the file, well, you can just transfer all the characters from the positions i + [end of the line to be deleted] + 1 to positions i + [start of the line to be deleted]. Or read the whole into a buffer and manipulate the characters there. But for such a task, line-based functions are more appropriate.

Upvotes: 2

aroth
aroth

Reputation: 54796

In a nutshell, yes, you can modify data at arbitrary positions in the file using random-access API methods. Of course, how the OS and filesystem handle this behind the scenes may result in the entire file being rewritten anyways.

Upvotes: 2

Andy
Andy

Reputation: 1484

Look at

int fseek (stream, offset, origin);

You can move to a specific offset and write a symbol there. But to find an offset of char to replace you still need to read all symbols before it.

Upvotes: 2

Related Questions