2013-12-23 77 views
0

我需要下面的結構寫入FIFO:寫多個字段(結構)先進先出

struct msg_t { 
    int length; 
    char* msg; 
}; 

我的malloc的結構和字符*裏面,我寫的是這樣的: (假設味精是變量名稱) write(fifo_fd,& msg,sizeof(msg_t));

從另一端讀取長度就好了。 字符串不是.. 如何用一次寫入來寫這兩個字段? 如果不是,兩個單獨的寫入是否好?

謝謝。

+0

爲了清楚起見,包括你想要做的一些代碼! – rullof

回答

2

你只會寫長度和指針地址,我懷疑你會在另一端想要什麼。我的猜測是你真正想要的是這樣的:

struct msg_t msg; 
// Initialise msg 
write(fifo_fd, &(msg.length), sizeof(int)); 
write(fifo_fd, msg.msg, msg.length); 
+0

謝謝..這就是我想到的,但是,我認爲有一種方法可以在一次寫作中做到這一點。 我想這是最正確的方法:) – dlv

+0

@dlv在一次寫入中有*方法可以做到這一點,但是它需要在數據存儲方面做一些準備工作。老實說,如果這完全是你想做的事情,那就麻煩了。這個答案會做你需要的。 (+1,btw)。 – WhozCraig

1

你考慮使用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; 
    } 
} 
+0

爲什麼使用'unsigned'而不是'size_t'作爲'length'的原因? – alk

+1

因爲OP使用了'int' ... –