gpt4 book ai didi

c - 读取 csv 文件时函数崩溃

转载 作者:太空宇宙 更新时间:2023-11-04 03:56:14 26 4
gpt4 key购买 nike

我已经编写了一个函数来读取 csv 文件,但是在解析过程中程序崩溃,在 strcat 中出现错误。错误出现在第三个字段,即电话。我无法发现我犯的错误在此阅读功能中。有人知道我要跟踪的地方吗?

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;
};

最佳答案

这里我试着总结一下:

sn = strtok(oneLine, " , ");
fn = strtok(NULL, " , ");
ph = strtok(NULL, " , ");
co = strtok(NULL, " , ");

您严重依赖正确的格式,但实际情况可能并非如此。

sn = strtok(oneLine, " , ");
fn = sn ? strtok(NULL, " , ") : NULL;
ph = fn ? strtok(NULL, " , ") : NULL;
co = ph ? strtok(NULL, " , ") : NULL;

if (!co) continue; // bad string

正如 BLUEPIXY 所说:

printf("\nCouldn't open %s...", "test.csv");

分配在 C 中看起来更简单:

head = malloc(sizeof(*head));

fgets 可能会失败:

if (fgets(oneLine, CONTACT_MAX, fptr) == NULL) break; // error, do something...

和未初始化的 head 变量(感谢 Kninnug):

struct contact *head = NULL; // otherise it contains garbage

关于c - 读取 csv 文件时函数崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16244886/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com