我正在研究使用 read() 函数来读取整个数据结构,每个数据结构的类型都与其他数据结构相同,但数据不同,然后将它们放入链表中。出于某种原因,我似乎找不到任何关于如何终止循环的具体信息,其中read(fp, &tmp, sizeof(struct foo))
包括new_node(tmp)
.
我希望能够简单地阅读直到 EOF,但我不知道如何使用 read() 函数确定 EOF 所在的位置。显然,我可以使用 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)当我阅读()时我变得乱码?