所以我有这段代码可以从 csv 文档中读取一堆行。我知道文档最初有 16 行,这就是我在 main 函数中指定 int noRows = 16;
的原因。
void readBeer(int noRows) {
char *oneline, *token;
char oneproduct[256];
char delim[] = ",";
int x = 1;
FILE *fp; //open file
if ((fp = fopen("varor.csv", "r")) == NULL) //can the file be opened?
{
fprintf(stderr, "File varor.csv couldn't be opened\n"); //"couldn't open file"
exit(-1);
}
while(noRows != 0)
{
int countTok = 1;
fgets(oneproduct, 256, fp); //get the first row
oneproduct[strlen(oneproduct) - 1] = '\0'; // remove end-of-line character
oneline = strdup(oneproduct); //duplicate oneproduct into oneline because strtok modifies the given string
token = strtok(oneline, delim); //split oneline into tokens, tokens are separated by ","
while (token != NULL)
{
if(countTok == 1) beer[x].productNumber = atoi(token);
else if(countTok == 2) strcpy(beer[x].name, token);
else if(countTok == 3) beer[x].price = atof(token);
else if(countTok == 4) beer[x].volume = atof(token);
else if(countTok == 5) strcpy(beer[x].type, token);
else if(countTok == 6) strcpy(beer[x].style, token);
else if(countTok == 7) strcpy(beer[x].packaging, token);
else if(countTok == 8) strcpy(beer[x].country, token);
else if(countTok == 9) strcpy(beer[x].manufacturer, token);
else if(countTok == 10) beer[x].alcohol = atof(token);
else printf("kossan hoppade!"); //should never be seen in console
token = strtok(NULL, delim);
countTok++;
}
x++;
noRows--;
free(oneline); free(token);
}
fclose(fp);
}
我的问题是如何在不知道文件有多少行的情况下读取文件的末尾?我正在考虑在文件中添加一个特定单元格,以便在控制台启动和关闭之间保存 noRows
。
我尝试使用char buffer[1000]; while(fgets(buffer, 1000, fp)) {}
但随后它读取前 8 行(不确定是否始终是 8)作为 0,0,0,0,0,0,0,0 ,0,0。
最佳答案
如果只是测试 fgets 的返回值,那么你的问题的答案
for (;;) // idiomatic C style for an infinite loop
{
int countTok = 1;
if (NULL == fgets(oneproduct, 256, fp)) break; //get one row and exit loop on EOF
...
但是正如评论中告诉您的那样,您的代码中还存在许多其他问题:
- 您将索引初始化为 1,而 C 数组索引从 0 开始。因此我假设
x=1;
应该是x=0;
。出于同样的原因,countTok = 1;
并没有错,但countTok = 0;
会更惯用 C - 您使用
fprintf(stderr, ...
)来注意到打开文件时的错误。虽然没有错误,但它没有给出错误原因。perror
会做... 您删除了
oneproduct
的最后一个字符而不控制它是换行符。这个假设是错误的- 如果一行至少包含 256 个字符
- 如果最后一行不以换行符结尾
惯用的方法是使用
strcspn
:oneproduct[strcspn(oneproduct, "\n")] = '\0'; // erase an optional end of line
- 您将
oneproduct
复制到oneline
。再说一次,没有任何问题,但它没有用,因为你从未使用原始行 - 一长串
else if
可以用开关代替,但这主要是风格问题 - 在循环结束时释放
token
。因为它是 NULL,所以它是一个无操作,但它没有被分配,所以不应该被释放。
关于c - 在c中读取csv文件的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48225481/