asdasdasd1234
asdasdasd1234

Reputation: 49

Segmentation fault in sscanf while reading FILE

When I compile my program I get no error, but when I start it I get a "Segmentation fault". The FILE I try to read is build like this:

322;Peter;m
233;Chad;m
211;Lisa;w

I have the strong feeling my sscanf function is the issue. Please help me.

#define MAXCHAR 30
#define MAXZEILE 40
void speicher(char Z[MAXCHAR]){

FILE *QUELL;
int a;
char n[MAXCHAR];
char g;
char string[MAXZEILE];
    QUELL=fopen(Z,"r");
    fgets(string, MAXZEILE, QUELL);
    sscanf(string, "%d;%s;%c", &a, n, &g);
    printf("%d, %s, %c", a, n, g);
    fclose(QUELL);
}

Upvotes: 1

Views: 155

Answers (3)

shaul boyer
shaul boyer

Reputation: 134

I assume that to your purposes the lines written below are enough

ReturnVal = sscanf(strinp1, "%d %c %100[^;] %c %c", &a, &Separator1, 
                   n,&Separator2, &g);
  1. Read an integer
  2. Read then the character ';'
  3. Read at most 100 characters, stop reading encountering the character ';'
  4. Read then again the character ;
  5. Read the next character. (man or woman???).

Upvotes: 0

Dennis Shtatnov
Dennis Shtatnov

Reputation: 1363

In your sscanf %s does not know when to stop:

sscanf(string, "%d;%s;%c", &a, n, &g);

Without properly tokenizing on ;, %s will keep grabbing input until the next whitespace (which in your case will be the end of the line). It should be changed to

sscanf(string, "%d;%[^;];%c", &a, n, &g);

The %[^;] specifies to grab characters that are not a ; thus achieving the desired result.

For more robustness, you may want to look into using strtok to first separate it ; and then process each individual segment.

Upvotes: 0

asdasdasd1234
asdasdasd1234

Reputation: 49

My bad: the MAXCHAR for the FILE input was to low. The FILE had more than 30 chars.

Upvotes: 1

Related Questions