0
我被給了一個文件來讀取,並將內容存儲在鏈接列表中。爲什麼我的代碼返回(空)時,我標記它?
文件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
也很好奇,其中分段故障的來源。這似乎很頻繁地發生在我身上。什麼是分段錯誤,以及如何避免它?它是上面(null)問題的一部分嗎?
我也僅限於使用C89。 – user2657410
一切都必須用「gcc -std = c89 -pedantic MyCode.c」進行編譯。 – user2657410