Alex Rivera | Logout

Change the current working directory in C++

Asked 2010-08-14T21:20:59.590
70

How can I change my current working directory in C++ in a platform-agnostic way?

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

Edit
Report

2 Answers

53

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 for most use cases.

answered 2010-08-14T21:33:11.810
5

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.

answered 2010-08-14T21:28:32.623

Your Answer