我得到了一个要读取的文件,并将其内容存储在一个链表中。
文件 schedule.csv 以逗号分隔,包含:
CSE1325.001,1,0,1,0,1,10:00,11:00
CSE1325.002,0,1,0,1,0,12:30,14:00
CSE2312.001,0,1,0,1,0,14:00,15:30
CSE2315.001,1,0,1,0,1,09:00,10:00
CSE2315.002,0,1,0,1,0,12:30,14:00
ENGL1301.004,0,1,0,1,0,11:00,12:30
HIST1311.001,0,0,0,0,1,13:00,16:00
MATH1426.005,1,0,1,0,0,16:00,17:30
每行包含一个课程编号,5 - 1 或 0(对于周一至周五,1 表示班级开会,0 表示班级不开会),然后是两个军事时间,说明班级开始和结束的时间。
到目前为止,我有:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
char course[15];
int mon;
int tue;
int wed;
int thu;
int fri;
char start[10];
char stop[10];
struct node *next;
};
typedef struct node link;
link *addque(char *course, char *mon, char *tue, char *wed, char *thu,
char *fri, char *start, char *stop);
int main(void)
{
FILE *fp;
char *schedule = "schedule.csv";
char buffer[15];
char *course, *del = ",";
char *mon, *tue, *wed, *thu, *fri;
char *start, *stop;
link *head = NULL, *temp, *tail;
if((fp = fopen(schedule, "r")) == NULL)
{
printf("unable to open %s\n", schedule);
exit(1);
}
while( fgets(buffer, sizeof(buffer), fp) != NULL)
{
/*---PROBLEM IS HERE!!!!---*/
course = strtok(buffer, del);
mon = strtok(NULL, del);
tue = strtok(del, NULL);
wed = strtok(NULL, del);
thu = strtok(NULL, del);
fri = strtok(NULL, del);
start = strtok(NULL, del);
stop = strtok(NULL, del);
/*---PROBLEM IS HERE!!!!---*/
printf("\n\n%s,%s,%s,%s,%s,%s,%s,%s\n\n", course, mon,
tue, wed, thu, fri, start, stop);
temp = addque(course, mon, tue, wed, thu, fri,
start, stop);
if(head == NULL)
head = temp;
else
tail->next = temp;
tail = temp;
}
fclose( fp );
}
link *addque(char *course, char *mon, char *tue, char *wed, char *thu,
char *fri, char *start, char *stop)
/**********************************************
name: addque
input: char *, 5x int *, 2x char *, course, days, times
output: struct node *, pointer to new node
*/
{
link *temp = malloc( sizeof(link) );
strcpy(temp->course, course);
strcpy(temp->start, start);
strcpy(temp->stop, stop);
temp->mon = atoi(mon);
temp->tue = atoi(tue);
temp->wed = atoi(wed);
temp->thu = atoi(thu);
temp->fri = atoi(fri);
temp->next = NULL;
return temp;
}
在对字符串进行标记后,我打印它以检查值。strtok 之后的 printf 不会出现在最终代码中。
无论如何,我的输出是:
CSE1325.001,1,(null),(null),(null),(null),(null),(null)
Segmentation fault
也很好奇分段错误来自哪里。这似乎经常发生在我身上。什么是分段错误,我该如何避免?它是上述(空)问题的一部分吗?