我有一个文本文件,其中包含随机数量的字符,数字,空格和新行。我想弄清楚如何找到这个文件的“长度”。例如:如果文本文件包含“这是一个示例”。长度应为19.我尝试使用sizeof(text_file)和strlen(text_file),但它们没有给我所需的输出。
我也尝试了这个:
void test(FILE *f){
int i;
i=0;
char ch;
while( ( ch = fgetc(f) ) != EOF )
{
printf("%c",ch); /*This is just here to check what the file contains*/
if(ch!='\0')
{
i=i+1;
}
}
printf("------------------\n");
printf("The length of the file is\n");
printf("%d",i); /*For some reason my length is always +1 what it actually should be*\
}
有没有更简单的方法来执行此操作,为什么上面的代码总是给+1?我想if语句有问题,但我不知道是什么。
提前感谢任何帮助。
答案 0 :(得分:2)
至于尺寸,你可以这样做:
size_t pos = ftell(f); // Current position
fseek(f, 0, SEEK_END); // Go to end
size_t length = ftell(f); // read the position which is the size
fseek(f, pos, SEEK_SET); // restore original position
如果你不关心这个位置,你当然可以省略重置当前的文件指针。
答案 1 :(得分:2)
正如其他人已经解释的那样,有更好的方法来确定文件大小。
你的代码没有给出预期结果的原因可能是你的
文件包含一个尾随换行符\n
,也计算在内:
This is an example.\n
是20个字符,而不是19个字符。
请注意,您应该为EOF检查声明int ch
,而不是char ch
要正常工作,请比较fgetc, checking EOF。