Reputation: 49
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
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);
Upvotes: 0
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
Reputation: 49
My bad: the MAXCHAR for the FILE input was to low. The FILE had more than 30 chars.
Upvotes: 1