views:

119

answers:

4

Hello,

I'm trying to figure out a way where I can change my current output directory using C++ code - and also need that method to be platform agnostic.

I found the direct.h header file which is Windows compatible, and the unistd.h which is UNIX/POSIX compatible. Any solutions?

Cheers.

+3  A: 

Does chdir() do what you want? It works under both POSIX and Windows.

Jeremy Friesner
+2  A: 

You want chdir(2). If you are trying to have your program change the working directory of your shell - you can't. There are plenty of answers on SO already addressing that problem.

Carl Norum
+6  A: 

The chdir function works on both POSIX (manpage) and Windows (called _chdir there but an alias chdir exists).

Both implementations return zero on success and -1 on error. As you can see in the manpage, more distinguished errno values are possible in the POSIX variant, but that shouldn't really make a difference.

AndiDog
So what header would I use for that? unistd?
sparkFinder
I'm asking since Visual Studio wants me to use direct.h, but when I try building the same code in Linux, it crashes on my head, saying that I need to use unistd.h
sparkFinder
@sparkFinder, you will usually need to include different headers on different platforms when dealing with nonstandard functions such as `chdir()`. IIRC, GCC will define `_WIN32` when targeting Windows, so you could use that with `#include` to choose a header.
RBerteig
@sparkFinder: You can check for Visual Studio with `#ifdef _MSC_VER` and then include the direct.h header. If it's not defined, use unistd.h. This should be enough as the other major programming environment on Windows, MinGW, has the unistd header.
AndiDog
You could just declare the prototype yourself.
R..
+2  A: 

Did you mean C or C++? They are completely different languages.

In C, the standard that defines the language doesn't cover directories. Many platforms that support directories have a chdir function that takes a char* or const char* argument, but even where it exists the header where it's declared is not standard. There may also be subtleties as to what the argument means (e.g. Windows has per-drive directories).

In C++, googling leads to chdir and _chdir, and suggests that Boost doesn't have an interface to chdir. But I won't comment any further since I don't know C++.

Gilles
In boost::filesystem, there wasn't a "chdir" when I used it last time.
rubber boots
@rubber: indeed, looking at http://www.boost.org/doc/libs/1_34_1/boost/filesystem/operations.hpp suggests that there is a `getcwd` equivalent but no `chdir` equivalent.
Gilles