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.