0

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?

user1701840
  • 1,062
  • 3
  • 19
  • 27

2 Answers2

3

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.

Community
  • 1
  • 1
Mike Sokolov
  • 6,914
  • 2
  • 23
  • 31
0

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

Rüppell's Vulture
  • 3,583
  • 7
  • 35
  • 49