A “segmentation fault” is the OS’s way of informing you that you tried to access memory that you are not allowed to touch.
Notice that in everyone’s code here we have used the
&
to get the address of the object you are trying to read with fscanf(). Your code lacks that very important piece. Again, read the docs.
If you want to read something (an integer, say) from file, you have to tell fscanf()
where to put the result.
1 2 3
|
int n;
if (fscanf( f, "%d", &n ) != 1)
FOOEY;
|
If you wish to read a double, the same applies:
1 2 3
|
double x;
if (fscanf( f, "%lf", &x ) != 1)
FOOEY;
|
The same applies for c-strings as well. The only difference is that the c-string is already addressed via pointer:
1 2 3
|
char s[100]; // 's' decays to a pointer, pointing to the first character to store
if (fscanf( f, "%99s", s ) != 1)
FOOEY;
|
The more explicit way to write it would be:
1 2 3
|
char s[100];
if (fscanf( f, "%99s", &(s[0]) ) != 1)
FOOEY;
|
Finally, notice how I use the very same structure every time. Attempt to read a single item, check that the read succeeded, and if not, bail. Again, “FOOEY” is just a place-holder for however you wish to handle the read error. Make sure to close the file.
Learning to do I/O in C is a pain, but once you get the basics it is pretty straight-forward.
Hope this helps.