简体   繁体   English

使用strsep读取csv文件的分段错误

[英]Segmentation Fault using strsep reading a csv file

I'm currently trying to read a csv file using strsep but it never passes the first line我目前正在尝试使用 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;
}

The output of this program is这个程序的输出是

public_repos id followers follower_list type following_list public_gists created_at following login
 
Segmentation fault (core dumped)

It prints the first line but not the rest.它打印第一行,但不打印其余行。

Thank you!谢谢!

The problem is that in this call问题是在这个电话中

strsep(&str, ";")

the pointer str is changed.指针str已更改。

For starters there is no great sense to reinitialize the pointer sp.对于初学者来说,重新初始化指针 sp 没有多大意义。

    char **sp = &str; 

    sp = &tmp;

You should write你应该写

char *pos = tmp;
char **sp = &pos; 

In this while loop you need to write在这个while循环中你需要写

    while ( ( token = strsep( sp, ";" ) ) ){
        
        printf("%s ", token);

    }

And then you need to free the both strings然后你需要释放两个字符串

free( str );
free( tmp );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM