我的工作是从文件中读取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;
}
}
}
}
发布于 2016-04-25 15:47:36
我休息了一下,然后干脆运行了我的代码,这没有任何意义。链表被搞乱了,我不知道我做的时候是怎么想的。但是我已经把它修好了,而且它起作用了
#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);
}
https://stackoverflow.com/questions/36840987
复制