c - Overwrite a line in a file -
i'm trying overwrite line in file contains unsigned long numbers. contents of file this:
1 2 3 4 5
i want replace specific number number 0. code wrote looks this:
file *f = fopen("timestamps", "r+"); unsigned long times = 0; int pos = 0; while(fscanf(f, "%lu\n", ×) != eof) { if(times == 3) { fseek(f, pos, seek_set); fprintf(f, "%lu\n", 0); } times = 0; pos = ftell(f); } fclose(f); f = fopen("timestamps", "r"); times = 0; while(fscanf(f, "%lu\n", ×) != eof) { printf("%lu\n", times); times = 0; } fclose(f);
the output of program looks this:
1 2 10 5
interestingly, if cat file, looks this:
1 2 10 5
am making mistake in ftell
? also, why didn't printf
show missing line cat
showed?
i reproduce , fix.
the present problem when open file in r+
must call fseek
@ each time switch reading writing , writing reading.
here, correctly call fseek
before writing 0
, not after write , following read. file pointer not correctly positionned , undefined behaviour.
fix trivial, replace :
if(times == 3) { fseek(f, pos, seek_set); fprintf(f, "%lu\n", 0); }
with
if(times == 3) { fseek(f, pos, seek_set); fprintf(f, "%lu\n", 0); pos = ftell(f); fseek(f, pos, seek_set); }
but beware : works here because replace line line of same length. if tried replace line containing 1000 line containing 0 line containing 0
on windows system end of line \r\n
, 00
on unix system end of line \n
.
because here happen (windows case) :
before rewrite :
... 1 0 0 0 \r \n ...
after :
... 0 \r \n 0 \r \n ...
because sequential file ... sequential serie of byte !
Comments
Post a Comment