使用 fscanf 时宽度作为变量
我正在尝试读取文件的特定部分,并且每行的数据量不同,但我知道我想要多少字节的信息。像这样:
5bytes.byte1byte2byte3byte4byte5CKSum //where # of bytes varies for each line (and there is no period only there for readability)
实际数据:
05AABBCCDDEE11
03AABBCC22
04AABBCCDD33
所以我想让我的宽度成为这样的变量:
fscanf_s(in_file,"%variableX", &iData);
这可能吗,因为现在我想我必须创建一个 case 语句?
I am trying to read in a certain portion of a file and that amount of data is different per line but I know how how many bytes of info I want. Like this:
5bytes.byte1byte2byte3byte4byte5CKSum //where # of bytes varies for each line (and there is no period only there for readability)
Actual data:
05AABBCCDDEE11
03AABBCC22
04AABBCCDD33
So I want to have my width be a variable like this:
fscanf_s(in_file,"%variableX", &iData);
Is this possible, because right now I'm thinking I have to create a case statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不幸的是,不,没有像 printf 的“*”这样的修饰符可以使 scanf 从变量获取其字段宽度或精度。最接近的是动态创建格式字符串:
Unfortunately, no, there's no modifier like '*' for printf that causes scanf to get its field width or precision from a variable. The closest you can come is dynamically creating the format string:
如果您确实希望能够以编程方式调整 fscanf 格式,您可以尝试堆栈分配一个具有足够空间的字符串,然后生成如下格式:
例如
If you really want to be able to adjust the fscanf format programmatically, you could try stack-allocating a string with enough space, and then generating the format like so:
e.g.
带有 %X 的 fscanf 会自动停在换行符处,对吗?如果字段确实以换行符结尾(如您的示例中所示),那么您不能直接调用
并让 fscanf 找出结尾在哪里吗?
fscanf with %X will stop at a newline automatically, right? If the fields really are newline-terminated (as in your example), then can't you just call
and let fscanf figure out where the end is?
您也可以考虑使用 C++ 流。
如果按照您的指示包含换行符,则更简单的方法是使用 getLine()。查看http://www.cplusplus.com/reference/iostream/ifstream/ 了解更多使用 read()、get()、getLine() 和许多其他出色流函数的方法。
You might also consider using C++ streams.
A simpler way if the newlines are included as you seem to indicate, would be to use getLine(). Check out http://www.cplusplus.com/reference/iostream/ifstream/ for more ways to use read(), get(), getLine() and lots of other great stream functions.
我认为最简单的方法是像这样使用 fread() :
I think the simplest would be to use fread() like this: