我目前正在尝试使用strsep读取csv文件,但它从不通过第一行
int main(){
FILE *fp = fopen("users100.csv", "r");
if(!fp){
printf("Erro");
return 0;
}
char *str;
str = (char *) malloc(10240);
while(fgets (str, 10240, fp) != NULL){
char *tmp = strdup(str);
char *token;
char **sp = &str;
sp = &tmp;
while(token = strsep(&str, ";")){
printf("%s ", token);
}
putchar('\n');
}
free(str);
fclose(fp);
return 0;
}此程序的输出为
public_repos id followers follower_list type following_list public_gists created_at following login
Segmentation fault (core dumped)它打印第一行,但不打印其余行。
谢谢!
发布于 2021-10-24 19:21:36
问题是在这个调用中
strsep(&str, ";")指针str已更改。
对于初学者来说,重新初始化指针sp没有多大意义。
char **sp = &str;
sp = &tmp;你应该写下
char *pos = tmp;
char **sp = &pos; 在这个while循环中,您需要编写
while ( ( token = strsep( sp, ";" ) ) ){
printf("%s ", token);
}然后您需要释放这两个字符串
free( str );
free( tmp );https://stackoverflow.com/questions/69699984
复制相似问题