scanf 来自 C/C++ 中的数据缓冲区

发布于 2024-12-11 03:52:00 字数 220 浏览 0 评论 0原文

我正在使用一个封闭的硬件,我想加载一个文本文件。我只有以下函数来访问辅助内存:

bool load_file(const char *filename, int **buf, int *size)

这意味着我最终会得到 buf 中的所有数据及其大小。如何从中提取字符串、整数或浮点数据?我想以与使用 scanf 类似的方式执行此操作。

谢谢。

I'm working with a closed piece of hardware and I want to load a text file. I only have the following function to access secondary memory:

bool load_file(const char *filename, int **buf, int *size)

This means I would end up with all the data in buf and the size of it in size. How could I extract strings, integers or float data from it? I would like to do it in a similar why as using scanf.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

请止步禁区 2024-12-18 03:52:00

您可以使用 sscanf 扫描内存块而不是文件,类似于使用 sprintfprintf 扫描到内存中。原型是:

int sscanf (const char *str, const char *format, ...);

换句话说,与 scanf 相同,但添加了一个指针。

那是为了将字符数据转换成其他类型。如果该内存缓冲区中有原始数据,则可以进行强制转换和取消引用。

换句话说,假设您有一个内存缓冲区,其中的整数从第五个位置(偏移量 4)开始,类似于:

#include <stdio.h>
int main(void) {
    //                +--------------+--> little-endian,
    //                |              |       32-bit = 42.
    char xyz[] = "1234\x2a\x00\x00\x00";
    int x = *((int*)(xyz+4));
    printf ("%d\n", x);
    return 0;
}

假设您的整数编码与我的相同,则输出 42(十六进制 2A)。一次一点地拆开这个表达式:

        (xyz+4)  : Get the address four unit past xyz. Since xyz is a char
                   pointer, this means four bytes.
  (int*)(xyz+4)  : Cast it into an int pointer.
*((int*)(xyz+4)) : De-reference that to get the int at that address.

You can use sscanf to scan memory blocks instead of files, similar to the way you can use sprintf to printf into memory. The prototype is:

int sscanf (const char *str, const char *format, ...);

In other words, the same as scanf but with a pointer added.

That's for turning character data into other types. If you have raw data in that memory buffer, you can cast and de-reference.

In other words, say you have a memory buffer with an integer starting at the fifth location (offset 4), something like:

#include <stdio.h>
int main(void) {
    //                +--------------+--> little-endian,
    //                |              |       32-bit = 42.
    char xyz[] = "1234\x2a\x00\x00\x00";
    int x = *((int*)(xyz+4));
    printf ("%d\n", x);
    return 0;
}

Assuming your integer encoding are the same as mine, this outputs 42 (hex 2A). Taking that expression apart one bit at a time:

        (xyz+4)  : Get the address four unit past xyz. Since xyz is a char
                   pointer, this means four bytes.
  (int*)(xyz+4)  : Cast it into an int pointer.
*((int*)(xyz+4)) : De-reference that to get the int at that address.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文