我有我的结构:
struct person{
char first_n[100];
char last_n[100];
char middle_n[100];
};
我尝试读取文件,然后将数据存储到链接列表节点中,然后根据char命令继续执行某些操作,但我的程序无限循环请求命令,并且我'已经被困了几个小时。我添加了一些打印语句,并注意到它在这个函数中是segfaulting:
void open_and_read(char* file){
FILE* fp = fopen(file_name, 'r');
if (filep != NULL){
while (!feof(fp)){
person* p = malloc(sizeof(person));
p->next = NULL;
while(fscanf(fp, "%s %s %s\n", p->first_n, p->last_n, p->middle_n) == 3){
add_to_contacts(p); //calls function to add node to front of linked list
}
}
}
}
char read_cmd(char* file_name){
char cmd;
printf("%s Command:", file_name); //ex: C:/user/word.txt Command:
scanf("%c", &cmd);
return cmd;
}
void add_to_contacts(person* p){
if (head_pointer != NULL){
p->next = head;
head = p;
return;
}
p->next = head;
head = p;
}
char* file_name = argv[1]; //assuming main takes in arguments.
open_and_read(file_name);
char cmd;
while (cmd != 'Q' or 'q'){
cmd = read_cmd(file_name);//calls simple function that returns char
evaluate_cmd(cmd); //if else statements to determine which functions to call
}
编辑:我已经看到了类似的问题,我相信每次创建新节点时都使用malloc尝试了解决方案。但是,我的问题仍然存在。