fopen always tries to load files from the working path. To reproduce the bug, I wrote a demo code below:
#include<stdio.h>
int main(void) {
FILE* my_file = NULL;
const char* file_name = "some_file.dat";
errno_t errcode = fopen_s(&my_file, file_name, "rb");
if (errcode != 0) {
printf("Cannot open the file `%s`. Error code = %d", file_name, errcode);
}
else {
puts("Success!!");
}
return errcode;
}
- I have a file
d:\path1\some_file.datand a directoryd:\path2. Then I compile the code above to the program namedD:\path1\myprogram.exe. - Input command
and the program will print "Success!!".cd d:\path1 myprogram - Input command
and the program will print "Cannot open the filecd d:\path2 ..\path1\myprogramsome_file.dat. Error code = 2".
My question is how to successfully open the file no matter where I run my program from. If fopen can't do this, is there a library that can do it?
Reply to the comments:
I know that fopen can load files from absolute paths but I want to make my program portable. myprogram.exe and some_file.dat are always in the same path.
Assuming that the file is in the same folder as the executable.
You can use the
argv[0]passed to the program – which is the executable name.I have shown it run three ways: two from the console, and one from GUI file manager.
Run from the console current directory
Run in the console from a parallel folder
Run from Windows file manager