banditKing
banditKing

Reputation: 9579

debugging fopen in C

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

Answers (3)

Saqlain
Saqlain

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

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

Here is what you should do to debug this:

  • Add printf to see what's inside the argv[1]
  • Make sure that the printed value matches the expected file name; if necessary, change the command line to look for an absolute path, i.e. ~myuser/somefile.dat or c:\myproject\somefile.dat rather than somefile.dat
  • Check that a file with that name exists in the current directory
  • Check that the user under which your program runs (usually, that's your user) has access permissions to read the file.

Upvotes: 4

Armen Tsirunyan
Armen Tsirunyan

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

Related Questions