如何正确读取csv文件 [英] How to correctly read in a csv file
本文介绍了如何正确读取csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在读取一个csv文件到一个结构但是当我检查是否填充了ointer时,我得到NULL,这会抛出我的错误消息。我已经在我的资源中包含了名为test.csv的文件,所以我'我不确定是什么导致了这个。我的阅读方法如下:
I''m reading in a csv file to a struct but when I get to check if the ointer is populated I get NULL which throws my error message.I have included the file named test.csv in my resources so I''m not sure what is causing this.My read method is as follows:
struct contact *readRecords(char *fileName, struct contact **ptrList)
{
struct contact *head, *newName;
FILE *fptr;
char oneLine[100];
char *sname, *fname, *phone, *company;
head = *ptrList;
fptr = fopen(fileName, "r");
if (fptr == NULL)
{
printf("\nCouldn't open %s", fileName);
return(head);
}
fgets(oneLine, 70, fptr);
while (!feof(fptr) )
{
fgets(oneLine, 70, fptr);
sname = strtok(oneLine, ",");
fname = strtok(NULL, ",");
phone = strtok(NULL, ",");
company = strtok(NULL, ",");
if(head == NULL)
{
head = (struct contact *)malloc(sizeof(struct contact));
*ptrList = head;
strcpy(head->sname, sname);
strcpy(head->fname, fname);
strcpy(head->phone, phone);
strcpy(head->company, company);
head->prev = NULL;
head->next = NULL;
}
else
{
head->next = (struct contact *)malloc(sizeof(struct contact));
head = head->next;
head->next = NULL;
strcpy(head->sname, sname);
strcpy(head->fname, fname);
strcpy(head->phone, phone);
strcpy(head->company, company);
}
}
fclose(fptr);
return(head);
} // end of read
推荐答案
你说:我已将名为test.csv的文件包含在我的资源中 - 这不会起作用。 fopen在您的默认目录中查找以变量filename命名的文件。如果filename包含完整路径规范,那么它就在那里。在任何情况下,fopen都不会尝试从您的.exe文件中提取资源。
You said: "I have included the file named test.csv in my resources" -- that won''t work. fopen is looking in your default directory for the file named in variable filename. If filename contains a full path specification, then it is looking there. In no case fopen will try to extract resources from your .exe file.
这篇关于如何正确读取csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文