Since C it\'s not a language I am used to program with, I don\'t know how to do this.
I have a project folder where I have all the .c and .h files and a conf folder unde
You're probably going to want to look into the dirent family of routines for directory traversal.
The location of your .c
and .h
files is not really the issue; the issue is the current working directory when you run your executable.
Can you not pass in the full path to the fopen()
function?
The easy way is to use an absolute path...
my_file = fopen("/path/to/my/file.txt", "r");
Or you can use a relative path. If your executable is in /home/me/bin
and your txt file is in /home/me/doc
, then your relative path might be something like
my_file = fopen("../doc/my_file.txt", "r");
The important thing to remember in relative paths is that it is relative to the current working directory when the executable is run. So if you used the above relative path, but you were in your /tmp
directory and you ran /home/me/bin/myprog
, it would try to open /tmp/../doc/my_file.txt
(or /doc/my_file.txt
) which would probably not exist.
The more robust option would be to take the path to the file as an argument to the program, and pass that as the first argument to fopen
. The simplest example would be to just use argv[1]
from main
's parameters, i.e.
int main(int argc, char **argv)
{
FILE *my_file = fopen(argv[1], "r");
/* ... */
return 0;
}
Of course, you'll want to put in error checking to verify that argc
> 2, etc.