Reputation: 9579
Im new to C and trying to read a file using the fopen command as follows:
FILE *f = fopen (argv[1], "rb" );
if(!f)
{
printf("ERROR! Unable to open file \n");
fclose(f);
return 1;
}
The file Im trying to read is "somefile.dat"
When I run this I get the following in the console
ERROR! Unable to open file
So f is null, but how do I debug this? I mean where do I start to look for the problem?
Thanks
UPDATE:
I tried te various suggestions below and found that the problem was it couldnt locate the file.
Im using XCode to run the program and XCode runs the executable in a different directory than where the files are placed so it couldnt find the file. I gave it a hard path and it worked.
The problem now is how to provide XCode the correct path to the file? Where does XCode run the executable?
Upvotes: 1
Views: 2770
Reputation: 17928
I can think of below possible reason can be
1) Path is incorrect
2) Permission of file somefile.dat are not correct so fopen fails
You can use errno to check what creating problem.
http://www.cplusplus.com/reference/cstdio/fopen/
http://www.cplusplus.com/reference/cerrno/errno/
Upvotes: 1
Reputation: 726569
Here is what you should do to debug this:
printf
to see what's inside the argv[1]
~myuser/somefile.dat
or c:\myproject\somefile.dat
rather than somefile.dat
Upvotes: 4
Reputation: 132994
First, hardcode your file's name. If the problem is gone, then the problem lies with your using argv.
Second, make sure the file exists. Try to open it in your explorer. Maybe it's somehow locked.
Thirs, use perror for a more descriptive error.
Hope you'll find your problem with these.
Upvotes: 2