c fscanf错误检查 [英] c fscanf error checking

查看:120
本文介绍了c fscanf错误检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用fscanf来读取C语言中的文件。我只是想知道我是否正确地检查了所有错误情况,这是最可靠的方法,因此我没有丢失任何东西。

I am using fscanf to read from a file in C. I was just wondering if I am correctly checking all the error conditions, and this is the most robust way to do so and I'm not missing anything.

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 ,则 ferror feof 必须返回非零。

scanf does not return EOF on "matching failure". It returns EOF only on "input failure" (EOF, read errors, or encoding errors), and only if the input failure happens before any successful conversion and assignment. Therefore, if the return value is EOF, either ferror or feof must return nonzero.

这篇关于c fscanf错误检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆