需要交换文件中每两行的内容,直到只剩下一行或所有行都被处理完。我不想使用另一个文件。
以下是我的代码:
#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);
//to get the total line count
while (!feof(fp)) {
fgets(line1, 100, fp);
i++;
}
i /= 2; //no. of times to run the loop
rewind(fp);
while (i-- > 0) { //trying to use !feof(fp) condition to break the loop results in an infinite loop
fgets(line1, 100, fp);
fgets(line2, 100, fp);
fsetpos(fp, &pos);
fputs(line2, fp);
fputs(line1, fp);
fgetpos(fp, &pos);
}
fclose(fp);
return 0;
}
content in this.txt:
aaa
b
cc
ddd
ee
ffff
gg
hhhh
i
jj
运行程序后的内容
b
aaa
ddd
cc
ddd
c
c
c
i
jj
我甚至试过使用fseek代替fgetpos,但结果仍然错误。经过我的推测,在第二个while循环运行两次后(即前四行已被处理),光标在第17个字节处是正确的(如调用ftell(fp)所返回的那样),并且第4行之后的文件内容没有改变,但由于某种原因,当第三次循环运行时调用fgets时,读入数组line1和line2的内容分别为"c\n"和"ddd\n"。再次强调,我不想使用另一个文件来完成这个任务,我只需要找出屏幕背后到底发生了什么问题。如果您有任何线索,请告诉我,谢谢!
fputs(line1,fp);
-->fputs(line1,fp);fflush(fp);
- BLUEPIXY