Current directory is pure evil

If you are developer, you should never use anything related to current directory. If you do, then with almost 100% probability you will regret that you did. Let me explain why you should never use it.

Current directory is state of your process. And it is not read only. Some code in your process can change it. And imagine you tested your code and made sure that it is safe to use current directory in that particular place. But tomorrow you or someone in your team will  refactor this code and move it in different part that it is not safe. For example, move that code to function that executes in different thread or threads. Good luck debugging that.

But you can say to me: “I checked all source code and there are no calls to function that change current directory. It is safe to use it!”. You are wrong.  There are many reasons for that that I found in practice:

  • you can search only for function in language runtime library and for example forgot about native Windows API function SetCurrentDirectory
  • You can use some 3rd party library that you have no source code and that code can change it under certain conditions
  • If your code ever calls for Open Dialog, Save Dialog then these functions will change current directory
  • User can start your app and pass working directory, and this will be current directory in your application. By default, it is the same as location of your application, but it can be changed from shortcut properties or when someone can start your application from their application
  • If your code runs inside different application, then rules can change any time and current directory can change from version to version

And again I would like to state that these are cases that I found in my practice. There could be much more cases to this problem but I hope that I demonstrate enough reasons to not use current directory.

And you should never change current directory. Again, because it is global state and if you change it then you changed for every single thread. There are always multiple ways to do the same but without change current directory.

And as result of everything I mentioned you should always use full directory and file path. Because otherwise you depend on current directory indirectly and all problems related to it.

Just in case Microsoft in operating system for handheld devices completely removed concept of current directory and that works totally fine so you can do the same.