It is supposed to exchange each line in the file until one line remains or all lines are exhausted. I do not want to use another file.
Here is my code:
#include <stdio.h>
int main() {
FILE *fp = fopen("this.txt", "r+");
int i = 0;
char line1[100], line2[100];
fpos_t pos;
fgetpos(fp, &pos);
while (!feof(fp)) {
fgets(line1, 100, fp);
i++;
}
i /= 2;
rewind(fp);
while (i-- > 0) {
fgets(line1, 100, fp);
fgets(line2, 100, fp);
fsetpos(fp, &pos);
fputs(line2, fp);
fputs(line1, fp);
fgetpos(fp, &pos);
}
fclose(fp);
return 0;
}
contents in this file:
aaa
b
cc
ddd
ee
ffff
gg
hhhh
i
jj
after starting the program
b
aaa
ddd
cc
ddd
c
c
c
i
jj
I even tried using fseekinstead fgetposto get the same wrong result.
, , , while (.. ), 17- , ( ftell(fp)), 4- - - , fgets , , line1 line2 - "c\n" "ddd\n" .
, , ,
. .