我得到了一个要读取的文件,并将内容存储在链接列表中。
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 %sn", 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("nn%s,%s,%s,%s,%s,%s,%s,%snn", 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
同样令人好奇的是,Segmentation错误是从哪里来的。这种事似乎经常发生在我身上。什么是分段错误,我如何避免它?这是上面(null)问题的一部分吗?
一个突出的直接问题是:
course = strtok(buffer, del);
mon = strtok(NULL, del);
tue = strtok(del, NULL); // <<<<
您对strtok
获取星期二值的论点是错误的。
然而,即使当修复时,由于以下原因,您也无法读取每一行:
char buffer[15];
:
while( fgets(buffer, sizeof(buffer), fp) != NULL)
:
由于buffer
的大小只有15,因此while
循环将而不是读取一整行。您需要使它至少与最长的行加上换行符和字符串终止符的几个字节一样大。