Tee Pee Tee Pee - 2 months ago 11
C Question

How to use fscanf for reading files in c(Segmentation Fault)?

I'm new user in

. I wrote this code in c and I have no problem and the output is correct.

#include <stdio.h>
#include <stdlib.h>

int main()
char *str[10];
FILE * fp;

fp = fopen ("file.txt", "w+");
fputs("We\nare\nin\n2016", fp);


fscanf(fp, "%s", str[0]);
fscanf(fp, "%s", str[1]);

printf("Read String1 |%s|\n", str[0] );
printf("Read String2 |%s|\n", str[1] );



but when I use char *str[15] instead of char *str[10], the result is segmentation fault. What is wrong?

usr usr

The pointers str[0] and str[1] are uninitialized. So, your program has undefined behaviour.

Either you need to allocate using malloc() or make them an array of arrays (e.g. str[2][256];) with fixed length that's sufficient enough for the strings you read from the file. In any case, I'd personally use fgets() instead of fscanf() and then parse the line as necessary.

It would also help to do error checking for all functions (fopen(), fscanf(), etc).