2

I have a C++ program compiled with MinGW on Windows 7 that calls fopen(), specifying a file with a relative path. The program works fine if you run the executable in it's own directory, but I've noticed that fopen() will not find the specified file if I were to run the program with command line in a different directory. For example, if my executable "foo.exe" and specified file "bar.txt" are located in "C:\project\build\" and I run the exe while in "C:\project\", fopen() will not find the file. Is there some workaround for this using the code or compiler flags?

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
user29112
  • 53
  • 1
  • 6
  • 2
    specify the absolute path? – anukul Dec 18 '16 at 05:58
  • or if you might move "project\", try something like [this](http://stackoverflow.com/questions/1528298/get-path-of-executable) – anukul Dec 18 '16 at 05:59
  • 2
    See this question: http://stackoverflow.com/questions/1528298/get-path-of-executable If necessary, you can cd to the directory containing the executable, with the expected consequences. – Dietrich Epp Dec 18 '16 at 06:01
  • 1
    Relative paths are always relative to the process current working directory. And the process current working directory is not fixed at time of compilation, the compiler have no concept of it so it can never be any workaround for it at time of compilation. – Some programmer dude Dec 18 '16 at 06:02
  • In fact, the process's current working directory is not fixed even at runtime. The process can change it for itself. – John Bollinger Dec 18 '16 at 06:05

1 Answers1

6

I can see this being necessary to access resources which are in a specified location relative to the executable, though without the absolute path of the executable file itself being known. I would suggest getting the absolute path to the executable file, probably using one of the methods described in Get path of executable, and then either changing the process's working directory to the parent directory of the executable, or constructing an absolute path to the file you want to open by resolving the relative path you have against that directory. Then you can pass the result to fopen().

Community
  • 1
  • 1
David Z
  • 128,184
  • 27
  • 255
  • 279