简体   繁体   English

在链表中插入从文件读取的不同字符串

[英]Inserting different strings read from file in a linked list

I'm writing a programm in c that reads words from a file, and adds the different from them in a linked list. 我正在用c编写一个程序,该程序从文件中读取单词,并将与它们不同的单词添加到链接列表中。 However, i don't get the right result.I have problem finding if a word exists in the list. 但是,我没有得到正确的结果。我在查找列表中是否存在单词时遇到问题。 Any help could be appreciated.Thanks. 任何帮助都将不胜感激。

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

struct list_el {
   char val[30];
   struct list_el * next;
};

typedef struct list_el item, item2;

void main() {

    item * curr, * head, * curr2, * head2;
    FILE *fp; 
    char words[30];
    int i;

    head = NULL;
    head2 = NULL;
    if ((fp=fopen("file.txt","r"))==NULL)
        printf("cannot open file\n");
    i=0;
    while (fscanf(fp,"%s",&words)!=EOF) {
        if (i!=0)
            while(curr2) {
                if  (!strcmp(words,curr2->val)){ 
                    break;
                }
                curr2 = curr2->next ; 
            }
        if (curr2==0 || i==0){
            curr = (item *)malloc(sizeof(item));
            curr2 = (item2 *)malloc(sizeof(item2));
            strcpy(curr->val,words);
            strcpy(curr2->val,words);
            curr->next  = head;
            curr2->next = head2;
            head = curr;
            head2 = curr2;
        }
        i++;
    }
    while(curr) {
      printf("%s\n", curr->val);
      curr = curr->next ;
    }
    fclose(fp);
}
int main(void) {//void main() is invalid.
    item *curr, *head = NULL;
    FILE *fp; 
    char words[30];

    if ((fp=fopen("file.txt","r"))==NULL){
        printf("cannot open file\n");
        return EXIT_FAILURE;//can't continue
    }
    while (fscanf(fp,"%29s", words) != EOF) {//remove &
        curr = head;
        while(curr) {//Search the current list
            if  (!strcmp(words, curr->val)){ 
                break;
            }
            curr = curr->next; 
        }
        if (curr == NULL){//not find words
            item *node = malloc(sizeof(*node));
            strcpy(node->val, words);
            node->next  = head;
            head = node;
        }
    }
    fclose(fp);

    curr = head;
    while(curr) {
      printf("%s\n", curr->val);
      curr = curr->next ;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM