I am trying to parse a given textfile, but so far, my program does not seem to be reading properly.
#include
int main(int argc, char *argv[])
{
Your code looks clear and straight-forward, but there is one important thing missing: error handling.
What happens if the file you want to open does not exist? fopen returns NULL in that case.
What happens if the file does not start with a number? fscanf returns the number of fields that have been successfully read, so you should check that the return value is at least 1.
You need to somehow handle these cases, probably by printing some error message and exiting the program. When you do that, be sure to include the relevant information in the error messages. Then you will find the bug that the other answers have already mentioned.
argv[0]
is the name of the program (./sjf
in your case), so you're trying to read in your own program's executable. Use argv[1]
instead to get the first real program argument.
One thing which immediatly comes to mind is that the program args include the executable name as the first element
argv[0]
is "sjf"
argv[1]
is "file.text"
so you should be using
fr = fopen (argv[1], "r");
Remember when debugging to always try and narrow the problem down, if you know the location of the error the cause often becomes obvious or at least investigatable.
In this case you should check argc >= 2
, print out argv[1]
to ensure you are trying to open the right file, then also check that the file was opened successfully.
Finally check the fscanf error codes to see that fscanf was able to read the number.