【发布时间】:2013-09-24 10:39:50
【问题描述】:
我得到的错误导航到 strcat.asm 文件并在主循环入口处设置了一个断点。我创建的 readFile 方法在此 strlen 循环中对字符串进行标记之前中断:
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 = sn ? strtok(NULL, " , ") : NULL;
ph = fn ? strtok(NULL, " , ") : NULL;
co = ph ? strtok(NULL, " , ") : NULL;
有人知道我在哪里出错了吗?
我的 readFile() 如下:
struct contact *readFile( struct contact *ptrList)
{
struct contact *head = NULL;
struct contact *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...", "test.csv");
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 = sn ? strtok(NULL, " , ") : NULL;
ph = fn ? strtok(NULL, " , ") : NULL;
co = ph ? strtok(NULL, " , ") : 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);
}
文件的格式是这样的:
姓、名、号码、公司
建造者,鲍勃,1234567,鲍勃的
未知,独家新闻,8765645,鲍勃的
【问题讨论】:
-
没有检查你的代码,但是从你的描述中暗示它可能是一个非 0 终止的字符串,这会造成问题,不是吗?
-
您对 strtok 的第一次调用是否有一个 NULL 指针作为参数?还是您的主要代码避免了这种情况?