我正在尝试学习 C,目前正在编写一个玩具脚本。现在,它只是打开一个文本文件,逐个字符地读取它,然后将其输出到命令行。
我查找了如何查看文件的大小(使用 fseek() 然后 ftell()),但它返回的结果与我在迭代时在 while 循环中计算字符得到的数字不匹配文件。
我想知道差异是否是由于 Windows 使用 \r\n 而不仅仅是 \n,因为差异似乎是#newlines+1。
以下是我正在处理的脚本:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * fp = fopen("test.txt", "r");
fseek(fp, 0, SEEK_END);
char * stringOfFile = malloc(ftell(fp));
printf("allocated %d characters for file\n", ftell(fp));
fseek(fp,0,SEEK_SET);//reset pointer
char tmp = getc(fp); //current letter in file
int i=0;
while (tmp != EOF) //End-Of-File (defined in stdio.h)
{
*(stringOfFile+i) = tmp;
tmp = getc(fp);
i++;
}
fclose(fp);
printf("Turns out we had %d characters to store.\nThe file was as follows:\n", i);
printf("%s", stringOfFile);
}
我得到的输出(你可以从输出中看到一个简单的测试文件)是:
allocated 67 characters for file
Turns out we had 60 characters to store.
The file was as follows:
line1
line2
line3
line4
line5
(last)line6
lmnopqrstuvw▬$YL Æ
其中打印的尾部位似乎是由于为字符串分配过多内存而产生的垃圾。
提前感谢您提供的任何帮助/答案!