Overwrite line in file

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", &times) != 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", &times) != 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?

+4
source share
2 answers

I could reproduce and fix.

, r+ fseek .

fseek , 0, . , undefined.

, :

if(times == 3)
{
    fseek(f, pos, SEEK_SET);
    fprintf(f, "%lu\n", 0);
}

if(times == 3)
{
    fseek(f, pos, SEEK_SET);
    fprintf(f, "%lu\n", 0);
    pos = ftell(f);
    fseek(f, pos, SEEK_SET);
}

BEWARE: , . , 1000 , 0, , 0 Windows, \r\n 00 unix- \n.

( Windows):

:

...  1  0  0  0 \r \n ...

:

...  0 \r \n  0 \r \n ...

... !

+2

(-) - , , , , , ( ) .

-

char line[1000];
FILE *original, *temporar;
original = fopen("original", "r");
temporar = fopen("temporar", "w");
while (fgets(line, sizeof line, original)) {
    processline(line);
    fprintf(temporar, "%s", line);
}
fclose(temporar);
fclose(original);
unlink("original"); // or rename("original", "original.bak");
rename("temporar", "original");

, .

0

Source: https://habr.com/ru/post/1584708/


All Articles