我需要下面的結構寫入FIFO:寫多個字段(結構)先進先出
struct msg_t {
int length;
char* msg;
};
我的malloc的結構和字符*裏面,我寫的是這樣的: (假設味精是變量名稱) write(fifo_fd,& msg,sizeof(msg_t));
從另一端讀取長度就好了。 字符串不是.. 如何用一次寫入來寫這兩個字段? 如果不是,兩個單獨的寫入是否好?
謝謝。
我需要下面的結構寫入FIFO:寫多個字段(結構)先進先出
struct msg_t {
int length;
char* msg;
};
我的malloc的結構和字符*裏面,我寫的是這樣的: (假設味精是變量名稱) write(fifo_fd,& msg,sizeof(msg_t));
從另一端讀取長度就好了。 字符串不是.. 如何用一次寫入來寫這兩個字段? 如果不是,兩個單獨的寫入是否好?
謝謝。
你只會寫長度和指針地址,我懷疑你會在另一端想要什麼。我的猜測是你真正想要的是這樣的:
struct msg_t msg;
// Initialise msg
write(fifo_fd, &(msg.length), sizeof(int));
write(fifo_fd, msg.msg, msg.length);
你考慮使用flexible array members(還解釋here)?見this ...所以聲明
struct msg_t {
unsigned length;
char msg[];
};
分配它與例如,
struct msg_t* make_msg(unsigned l) {
// one extra byte for the terminating null char
struct msg_t* m = malloc(sizeof(struct msg_t)+l+1;
if (!m) { perror("malloc m"); exit(EXIT_FAILURE); };
memset(m, 0, sizeof(struct msg_t)+l+1);
m->length = l;
return m;
}
然後用例如,
fwrite(m, sizeof(struct msg_t)+m->length+1, 1, fil);
,或者如果你使用write
做緩衝自己(因爲write
可以是部分!)如
void write_msg(int fd, struct msg_t *m) {
assert(m != NULL);
char* b = m;
unsigned siz = sizeof(struct msg_t)+m->length+1);
while (siz>0) {
int cnt=write (fd, b, siz);
if (cnt<0) { perror("write"); exit(EXIT_FAILURE); };
b += cnt;
siz -= cnt;
}
}
爲什麼使用'unsigned'而不是'size_t'作爲'length'的原因? – alk
因爲OP使用了'int' ... –
爲了清楚起見,包括你想要做的一些代碼! – rullof