fscanf / fscanf_s 行为差异
我对以下行为差异感到困惑:
// suppose myfile.txt contains a single line with the single character 's'
errno_t res;
FILE* fp;
char cmd[81];
res = fopen_s(&fp, "D:\\myfile.txt", "rb" );
fscanf(fp,"%80s",cmd); // cmd now contains 's/0'
fclose(fp);
res = fopen_s(&fp, "D:\\myfile.txt", "rb" );
fscanf_s(fp,"%80s",cmd); // cmd now contains '/0' !
fclose(fp);
结果不取决于调用顺序(即,首先调用 fscanf_s,您将首先得到空字符串)。在VC++-VS2005上编译。任何人都可以重现吗?谁能解释一下吗?
谢谢!
I'm puzzled by the following difference in behaviour:
// suppose myfile.txt contains a single line with the single character 's'
errno_t res;
FILE* fp;
char cmd[81];
res = fopen_s(&fp, "D:\\myfile.txt", "rb" );
fscanf(fp,"%80s",cmd); // cmd now contains 's/0'
fclose(fp);
res = fopen_s(&fp, "D:\\myfile.txt", "rb" );
fscanf_s(fp,"%80s",cmd); // cmd now contains '/0' !
fclose(fp);
The results do not depend in the order of call (i.e., call fscanf_s first, you'd get the empty string first). Compiled on VC++ - VS2005. Can anyone reproduce? Can anyone explain?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
来自
fscanf_s()
上的文档,http:// msdn.microsoft.com/en-us/library/6ybhk9kc.aspx:以及http://msdn.microsoft.com/en-us/library/w40768et。 ASPX:
所以你应该这样称呼它:
From the docs on
fscanf_s()
, http://msdn.microsoft.com/en-us/library/6ybhk9kc.aspx:And http://msdn.microsoft.com/en-us/library/w40768et.aspx:
So you should call it like so:
fscanf_s
(以及整个scanf_s
系列)要求您传递任何%c
、%C
、缓冲区本身之后的%s
、%S
或%[
;你忽略了这个论点:fscanf_s
(and the wholescanf_s
family) requires that you pass the size of any%c
,%C
,%s
,%S
, or%[
after the buffer itself; you're omitting that argument:您的问题标记为 C++,并且您正在 VC++ 中进行编译,但使用 fscanf?获取 std::ifstream。
Your question is tagged C++ and you're compiling in VC++, but using fscanf? Get a std::ifstream.
我认为有可能会产生误导结果:
相反,它应该是这样的:
其中
countof(cmd)
是分配给 cmd 的内存块的总大小,它必须大于 80,sizeof( cmd)
将为 4 或 8,在这种情况下会出错。I think there is a chance of misleading result in:
Instead it should be like:
where
countof(cmd)
is total size of memory block allocated to cmd which must be greater than 80,sizeof(cmd)
would be either 4 or 8 which will give error in the case.