c fscanf 错误检查

标签 c error-handling scanf

我正在使用 fscanf 从 C 语言的文件中读取。我只是想知道我是否正确地检查了所有的错误条件,这是最可靠的方法,我没有遗漏任何东西。

FILE* fp;
char filename[] = "untitled";
int count;

char item1[1025];
char item2[1025];


fp = fopen(filename, "r");
if (fp == NULL) {
    perror("fopen");
    return -1;
}

count = fscanf(fp, "%1024s%1024s", item1, item2);
if (count == EOF) {
    if (ferror(fp)) {
        perror("fscanf");
    }
    else {
        fprintf(stderr, "Error: fscanf matching failure\n");
    }
    return -1;
}
else if (count == 0) {
    fprintf(stderr, "Error: fscanf early matching failure\n");
    return -1;
}
else if (count != 2) {
    fprintf(stderr, "Error: fscanf matched less items than expected\n");
    return -1;
}

if (fclose(fp) == EOF) {
    perror("fclose");
    return -1;
}

感谢您的宝贵时间。

评论后编辑:

count = fscanf(fp, "%1024s%1024s", item1, item2);
if (count == EOF) {
    if (ferror(fp)) {
        perror("fscanf");
    }
    else {
        fprintf(stderr, "Error: fscanf reached end of file, no matching characters, no matching failure\n");
    }
    return -1;
}
else if (count != 2) {
    fprintf(stderr, "Error: fscanf successfully matched and assigned %i input items, 2 expected\n", count);
    return -1;
}

最佳答案

scanf 在“匹配失败”时不返回 EOF。它仅在“输入失败”(EOF、读取错误或编码错误)时返回 EOF,并且仅当输入失败发生在任何成功的转换和赋值之前。因此,如果返回值为 EOF,则 ferrorfeof 必须返回非零值。

关于c fscanf 错误检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5794420/

相关文章:

数一下总数文件中的关键字

c - 为什么这段代码与 bin 一起使用时会崩溃?

c - 为什么我的程序不能将大量 (>2GB) 保存到文件中?

c# - Xamarin表单未处理的异常记录

java - 使用旧框架生成Spring DataAccessExceptions

c++ - 从输入中获取未知数量的参数

c - 使用 fscanf 读取字符串,然后读取可变数量的整数到 EOF

c - 将数字读入字符

c++ - 如何检测隐藏进程

r - 如何让 R 在遇到错误时发送警报?