开发者

c fscanf error checking

开发者 https://www.devze.com 2023-03-01 01:12 出处:网络
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.

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;
}

Thank you for your time.

EDIT after comments:

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,开发者_C百科 "Error: fscanf successfully matched and assigned %i input items, 2 expected\n", count);
    return -1;
}


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.


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;
}

doesn't stand the test of usability. These cases are not distinguishable by the error message; if you must report both options to the user, then why not

if (count != NMATCHES)
    fprintf(stderr, "Error: wanted %d items, found %d\n", NMATCHES, count);


  1. Your fscanf works only when you use fprintf with the same %1024s%1024s, otherwise I don't think you can get the strings in the two char variables.

  2. You are limiting your code to take the size of 1K, you should never use hardcoding of values, and what will you do if you string size goes beyond 1K (extreme case), so you have to limit your string size in the file to be less than 1K, which you cannot expect everytime unless you have the control of writing the data to same file.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号