fscanf help: how to check for formatting

眉间皱痕 提交于 2019-12-12 03:03:24

问题


So the current function is supposed to see anything stored between two pound signs (#abc# should give back abc), but if I want to error check to see if there's a pound sign missing, or there's nothing between the pound signs, or that the length of the string in between the two pound signs is greater than a certain number of characters, do I use the fscanf function to do that?

Here's what the fscanf code looks like:

if (fscanf(fp, " %c%[^#]%c", &start, buffer, &end) == 3) {
    return strdup(buffer);      
} else { 
    return NULL; 

}


回答1:


do I use the fscanf function to do that?

No, you don't. Using the scanf() family of functions is very rarely a good idea.

char buf[0x1000];

// expect leading `#'
int ch = fgetc(fp);
if (ch != '#') {
    puts("Error, missing # at beginning of input");
    exit(-1);
}

// read until terminating `#' or until the buffer is exhausted
char *p = buf;
while ((ch = fgetc(fp)) != '#' && p - buf < sizeof(buf)) {
    *p++ = ch;
}

// expect terminating `#'
if (ch != '#') {
    puts("Error, missing # at end of input");
    exit(-1);
}



回答2:


If you need to deal with the zero-characters case, then probably fscanf() is not the right tool. There's a reasonable argument that fscanf() is seldom the correct tool; you'd do better with fgets() and sscanf().

In this case, I'd collect lines until there's one that's not blank (since that's what the fscanf() does), and then search for the # symbols with strchr():

char line[4096];
while (fgets(line, sizeof(line), fp) != 0)
{
    if (strspn(line, " \t\n") == strlen(line))
        continue;
    char *hash1 = strchr(line, '#');
    if (hash1 == 0)
        ...error no hashes...
    else
    {
        char *hash2 = strchr(hash1+1, '#');
        if (hash2 == 0)
            ...second hash is missing...
        if (hash2 - hash1 > MAX_PERMITTED_STRING_LEN)
            ...too long a string...
        *hash2 = '\0';
        char *res = strdup(hash1);
    }
}


来源:https://stackoverflow.com/questions/15985203/fscanf-help-how-to-check-for-formatting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!