使用C将CFG从文件读取到链接列表中

时间:2016-04-25 12:44:57

标签: c arrays file-io linked-list

我的工作是从文件中读取CFG并将其保存在链接列表中。然后遍历链表以删除空制作。 我的逻辑是在链表中使用一个数组。单个链表节点将指向其中值数组的数组。该阵列将保存一行CFG,直到换行。当一个' \ n'然后,将创建一个新节点,并指向一个数组。该过程将重复直到EOF。我编写了它但却出现了分段错误

/*the CFG
  S>ABe
  A>dB
  B>AS
*/
typedef struct node {
    //int val;
    struct node * next;
    char arr[5];//the array to save CFG per line
    }node_t;
int main() {
    node_t * head = NULL;
    head = malloc(sizeof(node_t));
    FILE *fp;
    char c; int i;
    fp = fopen("cfg.txt", "r");
    while((c = fgetc(fp)) != EOF) {
        head->next = malloc(sizeof(node_t));
        while(head->next != NULL) { //traverse till end of list
            head = head->next;
        }
        //now adding new line;
        for(i=0; i<5; i++) {
            head->next->arr[i] = c;
            if(c == '>'){
                continue;
            }else if(c == '\n') {
                break;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我休息了一下,干了我的代码,这没有任何意义。链接列表搞砸了,我不知道我做的时候在想什么。但是我已经修好了它并且它正在工作

    #include <stdio.h>
    #include <ctype.h>
    #include <stdlib.h>
    #include <stdbool.h>
    /*the CFG
      S>ABe
      A>dB|eS|e
      B>AS|b
    */
    typedef struct node {
        //int val;
        struct node * next;
        char arr[20];//the array to save CFG per line
        }node_t;
    int main() {
        node_t * head = malloc(sizeof(node_t));
        node_t * current = malloc(sizeof(node_t));
        node_t * root = malloc(sizeof(node_t));
        head = current;

        FILE *fp;
        char c, temp; int i; bool flag = true;
        fp = fopen("cfg.txt", "r");
        while((c = fgetc(fp)) != EOF) {
            if(c == '\n') {
              current->next = malloc(sizeof(node_t));
              //current->next->next = NULL;
              current = current->next;
              current->next = NULL;  
              flag = true;
            }else if(c == '>'){continue;}
            else if(c == '|'){
                current->next = malloc(sizeof(node_t));
                current = current->next;
                i = 0;
                current->arr[i] = temp;
                i++;
                continue;
            }
             else {
                current->arr[i] = c;
                i++;
                current->next = NULL;
                if(flag){
                    tmp = c;
                    flag = false;
                }
               // continue;
            }
        }
        root = head;
        while(root->next != NULL){
            for(i=0; i<20; i++) {
                printf("%c", root->arr[i]);
            }
            printf("\n");
            root = root->next;
        }
        fclose(fp);
    }