C 中的非贪婪 fscanf 和缓冲区溢出检查
我希望让 fscanf 识别何时发生潜在的溢出,但我不知道如何最好地做到这一点。
例如,对于包含字符串的文件
**a**bb**cccc**
,我会执行 a
char str[10];
while (fscanf(inputf, "*%10[^*]*", str) != EOF) {
}
,因为我保证 ** 和 ** 之间的值通常小于 10。但有时我可能会得到 a
**a**bb**cccc*
(没有最后一个 *),甚至可能出现缓冲区溢出。
我考虑过使用
while (fscanf(inputf, "*%10[^*]", str) != EOF) {
}
(没有最后一个 *)或什至
while (fscanf(inputf, "*%10s*", str) != EOF) {
}
,但这会返回整个字符串。我尝试查看是否可以检查是否存在 *,但我无法让它工作。我也见过 fgets 的实现,但我不想让它变得复杂。有什么想法吗?
I'm looking to have fscanf identify when a potential overflow happens, and I can't wrap my head around how best to do it.
For example, for a file containing the string
**a**bb**cccc**
I do a
char str[10];
while (fscanf(inputf, "*%10[^*]*", str) != EOF) {
}
because I'm guaranteed that what is between ** and ** is usually less than 10. But sometimes I might get a
**a**bb**cccc*
(without the last *) or even potentially a buffer overflow.
I considered using
while (fscanf(inputf, "*%10[^*]", str) != EOF) {
}
(without the last *) or even
while (fscanf(inputf, "*%10s*", str) != EOF) {
}
but that would return the entire string. I tried seeing if I could check for the presence or lack of a *, but I can't get that to work. I've also seen implementation of fgets, but I'd rather not make it complicated. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然 fscanf() 似乎被设计为通用表达式解析器,但很少有程序员依赖这种能力。相反,使用 fgets() 读取文本行,然后使用您选择或设计的解析器来剖析文本缓冲区。
使用 fgets() 的全部功能在不同的实现上是不可靠的,并且并不总是提供完整的功能,甚至也不能正确实现这些功能。
While
fscanf()
seems to have been designed as a general purpose expression parser, few programmers rely on that ability. Instead, usefgets()
to read a text line, and then use a parser of your choosing or design to dissect the text buffer.Using the full features of fgets() is dodgy on different implementations and doesn't always provide full functionality, nor even get those implemented right.
我不清楚你到底想要什么。是跳过任意数量的星号,然后将最多 9 个非星号字符读入缓冲区吗?如果是这样,请尝试以下操作:
您会注意到我没有使用
fscanf
。这是因为fscanf
几乎总是带来的麻烦多于它的价值。上面是更多的打字,但我可以确信它做了我所描述的事情。I'm not clear on exactly what you want. Is it to skip over any number of stars, and then read up to 9 non-star characters into a buffer? If so, try this:
You will note that I am not using
fscanf
. That is becausefscanf
is nearly always more trouble than it's worth. The above is more typing, but I can be confident that it does what I described it as doing.