0

I'm trying to read line input from a file, correctly parse the line, and add the three fields of information from the line onto a node in a linked list.

Here's my read from file function:

int readFile(char* file)
{
    FILE *fp = fopen(file,"r");

    char ch;
    char line[50];
    char string1[100];
    char string2[100];
    char string3[100];
    char endLine[2];

    int i = 0;
    while(fscanf(fp, "%[^\t]\t%[^\t]\t%[^\n]", string1, string2, string3) == 3)
    {
        printf( "%s\t%s\t%s\n", string1, string2, string3);
        addNode(string1, string2, string3, head, tail);
    }

    printNodes();
    fclose(fp);
    return 0;
}

And here is my addNode function:

// create stuff
Entry *entry = malloc(sizeof(Entry));
entry->name     = string1;
entry->address  = string2;
entry->number   = string3;

Node* node = malloc(sizeof(Node));
node->entry = entry;
node->next = NULL;

// Empty list
if(head->next == NULL)
{
    head->next = node;
}

// Else, add to the end of the list
else
{
    Node* temp = head->next;
    while(temp->next!= NULL) 
    {
        temp = temp->next;
    }

    temp->next = node;
}

I get problems when I call printNodes, and only the last read node's information is printed X times, where X is the number of unique nodes I'm supposed to have. I think I'm having a problem where I'm overwriting an old node each time I create a new node, but I'm not entirely sure, as this is my first time with raw C code.

Thanks again!

EDIT: here's the printNodes() function:

int printNodes(Node* head)
{
    Node *temp = head->next;

    while(temp->next != NULL)
    {
        printf("\n%s\t%s\t%s\n", temp->entry->name, temp->entry->address, temp->entry->number);
        temp = temp->next;
    }

    return 0;
}
LeoVannini
  • 95
  • 3
  • 11
  • 1
    If you think the problem is in the creation of new nodes, then cut out the file reader, hard-code some data, and see if the problem persists. – Beta Apr 13 '15 at 22:49
  • You need to provide the code for `printNodes()` along with the definitions of `Entry` and `Node`. – Andrew Henle Apr 13 '15 at 22:52
  • It is a good idea to write unit tests for each of your functions with their different scenarios, so you can have an idea what is working. For [C unit test](http://stackoverflow.com/questions/65820/unit-testing-c-code) I used to use [Unity](http://www.throwtheswitch.org/unity). – ericbn Apr 13 '15 at 22:54
  • 4
    `entry->name = string1;` --> `entry->name = strdup(string1);` – BLUEPIXY Apr 13 '15 at 22:55

1 Answers1

1

Your problem is here:

entry->name     = string1;
entry->address  = string2;
entry->number   = string3;

You are providing the same memory location to every node. Those strings contain the last value you read in when you call printNodes().

Andrew Henle
  • 32,625
  • 3
  • 24
  • 56