Romy Romy - 2 months ago 5x
C Question

Reading a line using fscanf()

I am trying to read a line from a file using fscanf():

int main()
FILE *fp;
char c, *string[4];
int i = 0,j[4];
fp = fopen("boil.txt", "r");
c = fgetc(fp);
if(fp == NULL)
{ printf("File read error\n");

while(c != '\n')
fscanf(fp, "%s %d ", string[i] , &j[i]);
c = fgetc(fp);
for(i = 0; i < 4; i++)
printf("%s %d\n", string[i], j[i]);

boil.txt is as follow:

boil 4 boilmilk 3 boilwater 5 heat 10

Why this program is giving Segmentation Fault?


Because you don't reserve space for such strings:

char *string[4];

is an array of pointers to string, but you need room to store those strings, something like:

char temp[256];

fscanf(fp, "%s %d ", temp , &j[i]);
string[i] = strdup(temp);


As pointed out by iRove, strdup is not part of the standard (but available on many implementations), if you can't use strdup, an alternative is:

string[i] = malloc(strlen(temp) + 1);
if (string[i] == NULL) {
strcpy(string[i], temp);

Don't forget to call free at the end (when the strings are no longer needed)

for (i = 0; i < 4; i++) free(string[i]);