I am trying to rewrite a line in a file that contains only unsigned long numbers. The contents of the file are as follows:
1
2
3
4
5
I want to replace a specific number with number 0. The code I wrote is as follows:
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 the program is as follows:
1
2
10
5
Interestingly, if I write a file, it looks like this:
1
2
10
5
Am I making a mistake in mine ftell? Also, why didnβt the printfmissing line show that it showed cat?
source
share