#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* getfield(char* line, int num) {
const char* tok;
for (tok = strtok(line, ",");
tok && *tok;
tok = strtok(NULL, ",\n"))
{
if (!--num)
return tok;
}
return NULL;
}
int main()
{
FILE* stream = fopen("b.csv", "r");
char line[1024];
char *pstr;int num;
const char* value;
while (fgets(line, 1024, stream))
{
char* tmp = strdup(line);
//printf("Field 3 would be %s\n", getfield(tmp, 3));
value=getfield(tmp, 3);
num =strtol(value,&pstr,10);
printf("Field 3 would be %d\n", num);
// NOTE strtok clobbers tmp
free(tmp);
}
}
/* b.csv
301,36,15
302,88,75
//我的输出
Field 3 would be 15
Field 3 would be 75
*/
问题是:/* b.csv
301,36,15
302,88,
,,,34
如果表被破坏如上“strtok”返回NULL,所以“strtol”给出“segfault”..如何解决它?
这里的主要问题是如果 2nd 不存在,它将 3rd 视为第二个并给出段错误!例如在 b.csv “,,,34” 的第三行中是否存在表示第三个值,但它的行为就像“34”是第一个值,第二个和第三个分别是 NULL !