gpt4 book ai didi

c - 使用 fscanf 检查是否存在更多行

转载 作者:行者123 更新时间:2023-11-30 15:48:55 27 4
gpt4 key购买 nike

我有这个函数可以从 txt 文件中读取数字,其结构如下:

1 2 5
2 1 9
3 5 8

该函数将值正确读取到我的值中,但我想检查我读取的行是否是文件中的最后一行。

下面函数中的最后一个 if 语句尝试通过查看 fscanf 是否生成 NULL 来执行此操作,但它不起作用,该函数始终返回 NULL,即使它不是最后一行。

 void process(int lineNum, char *fullName)
{
int ii, num1, num2, num3;

FILE* f;
f = fopen(fullName, "r");

if(f==NULL)
{
printf("Error: could not open %S", fullName);
}

else
{
for (ii=0 (ii = 0; ii < (lineNum-1); ii++)
{
/*move through lines without scanning*/
fscanf(f, "%d %d %d", &num1, &num2, &num3);
}

if (fscanf(f, "%*d %*d %*d\n")==NULL)
{
printf("No more lines");
}

fclose(f);

}
}

最佳答案

检查下面的代码。使用此代码可以查看是否已到达文件末尾。不建议使用 fscanf 读取文件末尾。

/* feof 示例:字节计数器 */

#include <stdio.h>

int main ()
{
FILE * pFile;
int n = 0;
pFile = fopen ("myfile.txt","r");
if (pFile==NULL) perror ("Error opening file");
else
{
while (fgetc(pFile) != EOF) {
++n;
}
if (feof(pFile)) {
puts ("End-of-File reached.");
printf ("Total number of bytes read: %d\n", n);
}
else puts ("End-of-File was not reached.");
fclose (pFile);
}
return 0;
}

关于c - 使用 fscanf 检查是否存在更多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16557659/

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