I tried to read the following line of 3 words in a file:
fruit|apple|lemon
char *type, *type2, *type3;
using this: fscanf(file, "%[^|]|%[^|]|%s", type, type2, type3);
but I am getting seg fault. anyone can help?
I tried to read the following line of 3 words in a file:
fruit|apple|lemon
char *type, *type2, *type3;
using this: fscanf(file, "%[^|]|%[^|]|%s", type, type2, type3);
but I am getting seg fault. anyone can help?
You need to make sure to allocate some space for the results. It appears from your example that type, type2, and type3 are all null. You need to point them at some storage on the heap or stack, like:
char type[64];
however be wary of buffer overflow here. See this other question for advice on how to avoid that.
Change the fscanf()
statement to this.It works.But make sure file
is of type FILE*
.Else if it is a string,you have to use sscanf()
:
fscanf(file, "%[^|]%*c%[^|]%*c%s", type, type2, type3);
//sscanf(file, "%[^|]%*c%[^|]%*c%s", type, type2, type3);
//Demo for the sscanf() case
#include<stdio.h>
int main()
{
char *file="fruit|apple|lemon",type[10],type2[10],type3[10];
sscanf(file, "%[^|]%*c%[^|]%*c%s", type, type2, type3);
printf("%s,%s,%s",type,type2,type3);
}
Output fruit,apple,lemon