1

So...what I'm trying to do is write a linked list into a file and then read it back in to a program again after terminating the program and restarting. I keep getting gibberish in when reading from the file to the linked list. In addition, I believe that the write() loop may be writing the same node repeatedly. I would like to know if I'm perhaps mixing something up. I don't seem to be able to find the problem with the code myself, for all that I've looked through the man pages and checked google.

The pertinent code:

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;
}

This is the output from the write loop:

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

The file is saved in binary, but I can make out enough to know that only the tail seems to be written, five times. I'm not sure why that is.

The output for the diagnostic printf's in the read loop is:

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

The output makes me think it's putting the value of the next pointer into the data int. Any idea why: 1) I might be write()ing the same node five times in a row? 2) I am getting gibberish when I read()?

4

1 回答 1

1

You have one too many levels of pointer indirection in your write call:

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

Remove the & from iter and you will write the data from your list node instead of the data stored at the pointer to your list node (possibly including other values from your stack that, subject to undefined behaviour).

At a glance, the rest of your code looks okay.

于 2013-12-02T02:06:00.053 回答