0

我有一个结构定义为

struct my_struct {
    struct hdr_str hdr;
    char *content; 
};

我试图通过将其全部嵌套为 read() 的参数来传递 my_struct 中第一个元素的内容

我所拥有的是

struct my_struct[5];

读定义为

ssize_t read(int fd, void *buf, size_t count);

我试图通过它作为

read(fd, my_struct[0].content, count)

但我收到 -1 作为返回值,带有 errno = EFAULT(错误地址)

知道如何将 read 读入结构数组中的 char * 吗?

4

1 回答 1

2

You'll need to allocate memory for read to copy data into.

If you know the maximum size of data you'll read, you could change my_struct to

struct my_struct {
    struct hdr_str hdr;
    char content[MAX_CONTENT_LENGTH]; 
};

where MAX_CONTENT_LENGTH is #define'd by you to your known max length.

Alternatively, allocate my_struct.content on demand once you know how many bytes to read

my_struct.content = malloc(count);
read(fd, my_struct[0].content, count);

If you do this, make sure to later use free on my_struct.content to return its memory to the system.

于 2012-10-24T19:46:04.260 回答