gpt4 book ai didi

在 C 中检查文本文件长度

转载 作者:太空宇宙 更新时间:2023-11-04 01:31:56 26 4
gpt4 key购买 nike

我有一个文本文件,其中包含随机数量的字符、数字、空格和换行符。我想弄清楚如何找到这个文件的“长度”。例如:如果文本文件包含“This is an example”。长度应为 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 语句有问题,但我不知道是什么。

非常感谢任何帮助,在此先感谢。

最佳答案

正如其他人已经解释过的,有更好的方法来确定文件大小。

您的代码没有给出预期结果的原因可能是您的文件包含尾随换行符 \n 也被计算在内:

This is an example.\n

是 20 个字符,而不是 19 个。

请注意,您应该为 EOF 检查声明 int ch,而不是 char ch正常工作,比较fgetc, checking EOF .

关于在 C 中检查文本文件长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21074084/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com