Opening file in a different dir. in C causes Segmentation Fault? Opening file in a different dir. in C causes Segmentation Fault? unix unix

Opening file in a different dir. in C causes Segmentation Fault?


You have a serious problem with this line:

while(fscanf(fin, "%lf", &n) != EOF){

because n is a float rather than a double. Because you're trying to write a 64-bit double into a 32-bit float, all bets are off (undefined behaviour).

The standard states that the l prefix "specifies that ... a following a, A, e, E, f, F, g, or G conversion specifier applies to an argument with type pointer to double".

For a float, you should just use %f. Or you could just make all your floating point types into double - I rarely use the float type anymore.


In addition, it's considered good practice to check return values from functions that use them to indicate errors (along with errno). If the fopen fails, then fin will be set to NULL and it would be a bad idea to then try and use that for reading data. Something like:

#include <errno.h>:fin = fopen("P1-DATA", "r");if (fin == NULL) {    printf ("Error %d opening input file\n", errno);    exit (1);}

would do. There are friendlier ways to do it but that will at least let you know if an error occurred and what the error was.


Based on your comment that this gives you an error code of 2 (ENOENT), it's because the file doesn't exist. You need to either be in the directory where your data file is when you run the program, or provide the full path name to it in the fopen.


Instead of specifying the name of the data file in your code, youcould instead specify it as a command-line parameter.

#include <err.h>#include <stdio.h>if (argv[1] == NULL)    err(1, "usage: %s datafile", argv[0]);if ((fin = fopen(argv[1], "r")) == NULL)    err(1, "Could not open \"%s\"", argv[1]);

(Note the check of the return value from fopen() above.)

You could then invoke your program with the path to the data file as acommand-line parameter:

% ./a.out /path/to/the/data/file

Note also that your data file appears to have more structure than asimple list of floating point numbers. Attempting to parse that datawith a simple "%f" format string is unlikely to work.