read()读指针或write()写错了数据?

时间:2013-12-02 01:58:39

标签: c file-io linked-list unistd.h

所以......我要做的是将链表写入文件,然后在终止程序并重新启动后再将其读回程序。从文件读取链接列表时,我一直在胡言乱语。另外,我认为write()循环可能重复写入同一个节点。我想知道我是否可能会混淆一些东西。我似乎无法自己找到代码的问题,因为我通过手册页查看并查看了谷歌。

相关代码:

struct test_t{
    int data;
    char buf[LEN];
    struct test_t * next;
};

struct test_t * new_node(struct test_t node, struct test_t * tail)
{
    struct test_t * tmp = NULL;

    if(!(tmp = malloc(sizeof(struct test_t))))
        return NULL;

    tmp->data = node.data;
    strcpy(tmp->buf, node.buf);
    tmp->next = NULL;
    if(tail)
        tail->next = tmp;

    return tmp;
}

...

while(read(fd, &tmp, sizeof(struct test_t)) == sizeof(struct test_t)){
    printf("%d, %s\n", tmp.data, tmp.buf);
    tail = new_node(tmp, tail);
    if(head == NULL)
        head = tail;
    printf("%d, %s\n", tail->data, tail->buf);
}

...

fd = open("test.txt", O_WRONLY | O_CREAT, 0666);
iter = head;
while(iter){
    printf("%d\n", write(fd, &iter, sizeof(struct test_t)));
    printf("%d, %s\n", iter->data, iter->buf);
    iter = iter->next;
}

这是写循环的输出:

112
1, a
112
2, b
112
3, c
112
4, d
112
5, e

文件以二进制文件保存,但我可以知道只有尾巴似乎写了五次。我不确定为什么会这样。

读取循环中诊断printf的输出是:

23728144, 
23728144, 
23728272, 
23728272, 
23728400, 
23728400, 
23728528, 
23728528, 
23728656, 
23728656,

输出让我觉得它将下一个指针的值放入数据int中。知道为什么: 1)我可能连续五次写同一个节点? 2)当我读()时,我会变得胡言乱语。

1 个答案:

答案 0 :(得分:1)

您的write电话中有一个太多级别的指针间接:

write(fd, &iter, sizeof(struct test_t))
          ^

&中删除iter,您将从列表节点写入数据,而不是存储在列表节点指针中的数据(可能包括堆栈中的其他值,受制于未定义的行为)。

乍一看,其余的代码看起来还不错。

相关问题