的fscanf求助:如何检查格式化 [英] fscanf help: how to check for formatting
问题描述
所以当前功能应该查看存储任何东西二镑符号之间(#ABC#应该还给ABC),但如果我想错误检查,看看是否有井号丢失,或者英镑符号之间没有什么,或者说,在这两个井号之间的字符串的长度超过一定数目的字符时,我用fscanf函数来做到这一点?
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?
这里是的fscanf code样子:
Here's what the fscanf code looks like:
if (fscanf(fp, " %c%[^#]%c", &start, buffer, &end) == 3) {
return strdup(buffer);
} else {
return NULL;
}
推荐答案
如果您需要处理零字符的情况下,则可能是的fscanf()
不是正确的工具。有一个合理的说法,的fscanf()
很少有正确的工具;你会使用与fgets()
和的sscanf()
。
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()
.
在这种情况下,我会收集行,直到有一个不为空(因为那是在的fscanf()
一样),然后搜索#
符号与和strchr()
:
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);
}
}
这篇关于的fscanf求助:如何检查格式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!