HxH HxH - 1 month ago 9
C Question

How to add char from a stream into a node?

Here is my code. I am stuck on add string of stream file into my linked list. For example, here I have a file called foo. In foo, it is formatted as following

12345678 12345678

1233 1389732

and so on. Which means I get each line of the file and only read the first string and add it into list. I checked add "a/b/c/d" on line 95.It works. So the insert function is working. The problem occurs on line 101. I don't know why the second line's value covered the first line's value.

Which means, when I print the list step by step, it prints out

a/b/c/d/12345678/

a/b/c/d/1233/1233/

I am stuck on why it did nit print a/b/c/d/12345678/1233 for second line?

Any suggestions about this?


#include <stdio.h>
#include <string.h>
#include <stdlib.h>


typedef struct n{
char *value;
struct n *next;
} Node;


void printList(Node *head){
Node *cur = head;
while(cur!=NULL){
printf("%s/", cur->value);
cur = cur->next;
}
printf("\n");
}

void insertIntoList(Node **head, char *data){
Node *newNode = malloc(sizeof(Node));
if (newNode == NULL){
perror("Failed to allocate a new node for the linked list");
exit(1);
}
newNode->value = data;
newNode->next = NULL;

Node *currentList = *head;
if(*head == NULL){ //if the linked list head is null, then add the target into linked list
*head = newNode;
}
else{
while(currentList->next!=NULL){
currentList = currentList->next;
}
currentList->next = newNode;
}
}


int main(int argc, char**argv){
FILE *fileStream;


size_t len = 0;
char *line = NULL;
Node *head = NULL;


int j;
for(j=1; j<argc-2;j++){
fileStream = fopen(argv[j], "r");
if(fileStream == NULL){
fprintf(stderr, "could not open");
continue;
}
insertIntoList(&head,"a"); /////////////Line 95
insertIntoList(&head,"b");
insertIntoList(&head,"c");
insertIntoList(&head,"d");
printf("here is a try\n");
printList(head);
while(getline(&line, &len, fileStream)!=EOF){ /////////////Line 101
char *targetNum = strtok(line, " ");
if(strcmp(targetNum, "\n")!=0&&strcmp(targetNum,"\t")!=0&&strcmp(targetNum," ")!=0){
printf("*****%s\n", targetNum);
insertIntoList(&head, targetNum);
printf("######print head here is##########\n");
printList(head);
printf("######print head here is##########->\n");
}
}
//printList(head);
}
return 0;
}



Answer

The reason is, that you are only storing the pointer in your list, not the actual data.

The first 4 items all have different memory locations, so they remain distinct.

But the next two have the same memory location, so the data is the same for both, which is the most recent data placed at that location.