c - read() 读取指针或 write() 写入错误数据?

标签 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) 当我读 () 时我变得乱码?

最佳答案

您的 write 调用中的指针间接级别过多:

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

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

乍一看,您的其余代码看起来没问题。

关于c - read() 读取指针或 write() 写入错误数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20319687/

相关文章:

c - 根据子字符串查找删除列表条目

c - 这个C函数有什么作用?

c - Strstr 返回 NULL

c - 读取不一致的文件

c++ - 如何 CloseHandle 转换为 FILE* 的句柄?

c - 在链表中插入元素到列表中最大元素之后

c - 256如何用char表示?

c++ 11 - 使用目录

c - 通过堆栈推送的指针引用传递

C 将链表写入文件