1

I'm currently trying to read a csv file using strsep but it never passes the first line

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!

1
  • You free(str) but hasn't str been modified by strsep()? What are tmp and sp for? Commented Oct 24, 2021 at 19:17

1 Answer 1

2

The problem is that in this call

strsep(&str, ";")

the pointer str is changed.

For starters there is no great sense to reinitialize the pointer sp.

    char **sp = &str; 

    sp = &tmp;

You should write

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

In this while loop you need to write

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

    }

And then you need to free the both strings

free( str );
free( tmp );
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the answer, I did not realize that i needed to use sp in the while loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.