我编写了一个读取 csv 文件的函数,但在解析过程中途程序崩溃给我 strcat 中的错误。错误出现在第三个字段是 phone。我无法发现我在此读取中犯的错误功能。有人知道我要去哪里吗?
struct contact *readFile( struct contact *ptrList)
{
struct contact *head, *newContact;
FILE *fptr;
char oneLine[CONTACT_MAX];
char *sn, *fn, *ph, *co;
head = ptrList;
//open test.csv to be read
fptr = fopen("test.csv", "r");
if( fptr == NULL )
{
printf("\nCouldn't open %s...");
return(ptrList);
}
fgets(oneLine, CONTACT_MAX, fptr);
while( !feof(fptr) )
{
fgets(oneLine, CONTACT_MAX, fptr); // process the next line to be tokenized
if (oneLine[strlen(oneLine) - 1] == '\n')
{
oneLine[strlen(oneLine) - 1] = '\0';
}
sn = strtok(oneLine, " , ");
fn = strtok(NULL, " , ");
ph = strtok(NULL, " , ");
co = strtok(NULL, " , ");
if ( head == NULL )
{
head = (struct contact *)malloc(sizeof(struct contact));
ptrList = head;
strcpy(head->fName,fn);
strcpy(head->sName,sn);
strcpy(head->phone,ph);
strcpy(head->company,co);
head->prev = NULL;
head->next = NULL;
}
else
{
newContact = (struct contact *)malloc(sizeof(struct contact));
head->next = newContact;
newContact->prev = head;
newContact->next = NULL;
strcpy(newContact->fName, fn);
strcpy(newContact->sName, sn);
strcpy(newContact->phone, ph);
strcpy(newContact->company, co);
head = newContact;
} // end of (ptrList == NULL)
} // end of while( !feof(fptr))
fclose(fptr);
return(ptrList);
这就是我定义联系的方式:
struct contact {
char sName[CONTACT_MAX+1];
char fName[CONTACT_MAX+1];
char phone[CONTACT_MAX+1];
char company[CONTACT_MAX+1];
struct contact *prev;
struct contact *next;
};