因此当前函数应该看到存储在两个井号之间的任何内容(#abc# 应该返回 abc),但是如果我想错误检查以查看是否缺少井号,或者井号之间没有任何内容,或者两个井号之间的字符串长度大于一定数量的字符,我是否使用 fscanf 函数来做到这一点?
fscanf 代码如下所示:
if (fscanf(fp, " %c%[^#]%c", &start, buffer, &end) == 3) {
return strdup(buffer);
} else {
return NULL;
最佳答案
do I use the fscanf function to do that?
不,你不知道。使用 scanf()
系列函数很少是个好主意。
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);
}
关于c - fscanf 帮助 : how to check for formatting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15985203/