【问题标题】:read() reading pointers or write() writing the wrong data?read() 读取指针或 write() 写入错误数据?
【发布时间】:2023-03-18 20:34:01
【问题描述】:

所以...我要做的是将链接列表写入文件,然后在终止程序并重新启动后再次将其读回程序。从文件读取到链表时,我一直在乱码。另外,我相信 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) 我可能连续五次对同一个节点进行 write()? 2)当我阅读()时我变得乱码?

【问题讨论】:

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


    【解决方案1】:

    write 调用中的指针间接级别太多了:

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

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

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

    【讨论】:

    • 就是这样。谢谢。现在完美运行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多