我正在处理一个示例问题,我必须使用 fseek() 和 ftell() 反转文本文件中的文本。我成功了,但是将相同的输出打印到文件中,我得到了一些奇怪的结果。我输入的文本文件如下:
redivider
Racecar
kayak
civic
level
refer
这些都是回文
命令行中的结果效果很好。然而,在我创建的文本文件中,我得到以下内容:
ÿsemordnilap lla era esehTT
referr
levell
civicc
kayakk
racecarr
redivide
我从这个问题的答案中知道这对应于 C 中 EOF 的文本文件版本。我只是对为什么命令行和文本文件输出不同感到困惑。
#include <stdio.h>
#include <stdlib.h>
/**********************************
This program is designed to read in a text file and then reverse the order
of the text.
The reversed text then gets output to a new file.
The new file is then opened and read.
**********************************/
int main()
{
//Open our files and check for NULL
FILE *fp = NULL;
fp = fopen("mainText.txt","r");
if (!fp)
return -1;
FILE *fnew = NULL;
fnew = fopen("reversedText.txt","w+");
if (!fnew)
return -2;
//Go to the end of the file so we can reverse it
int i = 1;
fseek(fp, 0, SEEK_END);
int endNum = ftell(fp);
while(i < endNum+1)
{
fseek(fp,-i,SEEK_END);
printf("%c",fgetc(fp));
fputc(fgetc(fp),fnew);
i++;
}
fclose(fp);
fclose(fnew);
fp = NULL;
fnew = NULL;
return 0;
}
没有错误,我只想要相同的输出。