【发布时间】:2018-01-12 11:35:08
【问题描述】:
所以我有这段代码可以从 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。
【问题讨论】:
-
您是否尝试检查您是否达到 EOF?顺便说一句:您确定最后一行包含值的末尾包含
\n吗? -
请使用 switch(),其他很多 if-s 看起来很糟糕。
-
当我使用缓冲区时,它在最后一行之后停止,所以它注册了 EOF,是的。最后一行的 \n 有什么关系?
-
@Gnqz 我通常希望它在我让它看起来不错之前工作,但我会编辑它。
-
关于您的实际问题:您重新设计的尝试很有希望。尝试
getline()而不是fgets()。如果失败则返回-1。