0
當我試圖解析一個文本文件,然後在單獨鏈接列表中打印內容時,每個值都由於某種原因被第二個最後一個值所覆蓋。例如,如果列表是爲什麼這會取代初始值?
一個
b
Ç
d
代碼打印這些適當的線while循環內,但後來當我嘗試在代碼的末尾打印頭字符串,代碼將只爲頭和頭的下一個值打印d。
char buf[1024];
printf("Enter the file name: ");
fgets(buf, 1024, stdin);
char *file_name = strtok(buf, "\n");
FILE *fp;
fp = fopen(file_name2, "r");
char *throwaway = fgets(buf, 1024, fp);
struct bit_t *tail;
struct bit_t *head;
head = create_node(throwaway);
printf("%s\n", head->pos1);
int count;
count = 0;
//issue is that it is just overwriting the old results
while((fgets(buf, 1024, fp)) != NULL) {
printf("String : %s\n", buf);
tail = insert_tail(head, create_node(buf));
printf("%s\n", tail->pos1);
}
printf("Results : \n");
printf("%s\n", head->pos1);
printf("%s\n", head->next->pos1);
struct bit_t *create_node(char *pos1)
{
struct bit_t *r;
struct bit_t *current;
r = malloc(sizeof(struct bit_t));
if(!r) {
exit(1);
}
r->next = NULL;
r->pos1 = pos1;
current = r;
return current;
}
struct bit_t *insert_head(struct bit_t *head, struct bit_t *node)
{
node->next = head;
head = node;
return node;
}
struct bit_t *insert_tail(struct bit_t *head, struct bit_t *node)
{
struct bit_t *current;
current = head;
while(current->next != NULL) {
current = current->next;
}
current->next = node;
return node;;
}
結構開始使用的是
struct bit_t {
char *pos1;
struct bit_t *next;
};