views:

210

answers:

3

I understand SetCurrentDirectory shouldn't be used in a multithreaded application since the current directory is shared between all threads in the process.

What is the best approach to setting the directory with this in mind. It can mostly be avoided setting the directory by including the full pathname when opening files instead of first navigating to them with SetCurrentDirectory, but is this the only solution?

+1  A: 

Each process has a single current directory, so if you want each thread in your process use different current directory I think you should specify the full path in each.

Ahmed Said
+4  A: 

I've encountered this problem before.

Any object that needs the concept of a current directory to support relative paths or searching (e.g. a build tool) has a member property that it maintains with its "current" path, then build the full path to open/create/search.

The initial value for CurrentPath can be retrieved once during the application's load phase, e.g. main(), WinMain(), DllInit(), etc. via GetCurrentDirectory and stored in a global. After that the Win32 version is ignored.

The OPENFILENAME structure has an initial directory member, so file open/save dialogs don't have to use the Win32 current directory.

devstuff
A: 

A advice to use full paths in general and local paths only as a exception (and very carefully), when needed. I.e. the OpenFile Dialog may or may not change the current directory (depending on attributes) etc. Using filenames or local paths is a potential cause of trouble.

By my experience full paths do not slow down file access significantly. I wrote a app that opens thousands of files every minute and writes sorted data to other thousands of files - all using full paths and all on a windows mounted network drive. The bottleneck there was closing the files. Not opening them.

RED SOFT ADAIR