-1

I have to do a simple task. I have to open a file which is in a directory. I have the .c file in src, when I compile I move the programs (a.out) in the a bin directory. I want to read a file in the directory asset. All these folders are in a main folder.

If I do this

FILE* fp = fopen("../asset/team_list", "r");

it won't open the file. Why can't I open the file in that directory?

3
  • possible duplicate of stackoverflow.com/questions/2925241/… Jun 10, 2014 at 9:47
  • @Amk,What is the error saying ? If error found using perror function
    – Kalanidhi
    Jun 10, 2014 at 9:58
  • As explained in the duplicate, fopen is relative to the cwd. In this case you are most likely going up a level (..) when you should not. If this is not the case then your question does not contain enough information to answer it (which, to be honest, it already does not).
    – Jongware
    Jun 10, 2014 at 10:24

3 Answers 3

0

guess you forgot to put the extension of your file

FILE* fp = fopen("../asset/team_list.doc", "r");
1
  • @Amk relative file names are relative to the current working directory, which might not be where the executable is located. Which directory are you at when you run your program ?
    – nos
    Jun 10, 2014 at 10:20
0

Find what error you get using perror/explicit mention of error message and expect a possible reply from stackoverflow.

  • Make sure you are pointing out to the correct directory where the file is present from the PWD from where your program is being executed.
0

Relative paths are relative to the current working directory of the process, which might not be the same location as the binary file. So, if you are in /home/user/ and you run ./project/bins/my.exe then your current working directory is /home/user/, relative paths need to be relative to that location.

You can try a few things to help with this issue. First, after the failed open you could examine errno to see why the open failed, is it permissions, invalid path?

Alternatively you might have access to the strace program, this traces system calls, like open from your application, and will allow you to see the failed system call. Try strace ./project/bins/my.exe, you'll see a lot of output, dig through this looking for the failed open call, and try to figure out why this is failing, again the errno will be included in the trace to help understand the failure.

Lastly, you could just add a call to getcwd to your program and print the result (as a debugging aid), this places the current working directory into a buffer, something like this:

char buffer [PATH_MAX + 1];
getcwd (buffer, PATH_MAX + 1);
printf (buffer);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.