Romy Romy - 3 months ago 12
C Question

Reading a line using fscanf()

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

#include<stdio.h>
#include<stdlib.h>
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");
exit(0);
}

while(c != '\n')
{
fscanf(fp, "%s %d ", string[i] , &j[i]);
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?

Answer

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);

EDIT:

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) {
    perror("malloc");
    exit(EXIT_FAILURE);
}
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]);