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

时间:2016-05-26 18:49:38

标签: c list file pointers struct

我在c中编写一个程序来读取文件中的单词,并在链接列表中添加不同的程序。但是,我没有得到正确的结果。如果列表中存在单词,我会发现问题。任何帮助都可以得到赞赏。谢谢。

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

1 个答案:

答案 0 :(得分:2)

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