[英]reading CFG from a file into a linkedlist using C
我的工作是從文件中讀取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;
}
}
}
}
我休息了一會,干了我的代碼,這沒有任何意義。 鏈接列表被弄亂了,我不知道自己在想什么。 但我已經修復它並且它正在工作
#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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.