所以我已经读了很多关于为什么feof不能正常工作的帖子,它们都使用while(fscanf(...) == 1)来读取文件末尾,我的问题是我有不同于每个循环的临时值,因为它读取处理它的每一行,然后移动到下一行。我目前使用的代码可以正确地读取所有输入,但会打印最后一行两次。我想知道是否有更好的方法来做这件事,而不是只做一个hack工作并删除最后处理的行,因为它被处理了两次。
void readInputFile(Customer customers[]) {
FILE *input = fopen("hw4input.txt", "r");
while (!feof(input)) {
char tempName[MAXNAMELEN];
int tempQuantity;
char tempItem[MAXNAMELEN];
double tempPrice;
fscanf(input, "%s %d %s $%lf", &tempName, &tempQuantity, &tempItem, &tempPrice);
printf("%s %d %s %.2lf\n", tempName, tempQuantity, tempItem, tempPrice);
}
printf("EOF\n");
fclose(input);
} 发布于 2017-07-16 04:00:59
在尝试读取文件之前,不能使用feof()检测文件结尾。仅在尝试从文件读取数据失败后,feof()才会返回文件结束状态的状态。
相反,您应该使用fscanf()从流中读取值,或者使用fgets()使用更健壮的解析器:
void readInputFile(Customer customers[]) {
FILE *input = fopen("hw4input.txt", "r");
if (input != NULL) {
char name[1024];
int quantity;
char item[1024];
double price;
while (fscanf(input, "%1023s %d %1023s %lf", name, &quantity, item, &price) == 4) {
printf("%s %d %s %.2lf\n", name, quantity, item, price);
}
printf("EOF\n");
fclose(input);
} else {
printf("Cannot open input file\n");
}
}发布于 2017-07-16 03:38:04
我想知道是否有更好的方法来做这件事,而不是只做一个hack工作并删除处理的最后一行。
是的,有。
检查代码中来自fscanf的返回值。当您尝试读取超过文件末尾的内容时,调用将失败。
不管怎样,你都应该去检查一下。甚至有很多人在这里发帖,他们会认为你无论如何都不应该使用任何*scanf()函数,因为它们即使不是不可能以任何健壮的方式使用,也是非常困难的。几乎总有一种方法可以将会导致问题的数据提供给某个*scanf()函数。
https://stackoverflow.com/questions/45122048
复制相似问题