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

时间:2011-10-20 12:18:25

标签: c++ c file scanf

我正在处理一个封闭的硬件,我想加载一个文本文件。我只有以下功能来访问辅助存储器:

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

这意味着我最终将获得buf中的所有数据及其大小。我怎样才能从中提取字符串,整数或浮点数据?我想做与使用scanf类似的原因。

感谢。

1 个答案:

答案 0 :(得分:4)

您可以使用sscanf扫描内存块而不是文件,类似于将sprintf printf用于内存的方式。原型是:

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

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

这是将字符数据转换为其他类型。如果您在该内存缓冲区中有 raw 数据,则可以进行转换和取消引用。

换句话说,假设你有一个内存缓冲区,其整数从第五个位置开始(偏移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.