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