#include <windows.h>
#include <iostream>
int main() {
constint bufferSize = MAX_PATH;
char oldDir[bufferSize]; // store the current directory
// get the current directory, and store it
if (!GetCurrentDirectory(bufferSize, oldDir)) {
std::cerr << "Error getting current directory: #" << GetLastError();
return 1; // quit if it failed
}
std::cout << "Current directory: " << oldDir << '\n';
// new directory
constchar* newDir = R"(C:\path\to\directory\)"if (!SetCurrentDirectory(newDir)) {
std::cerr << "Error setting current directory: #" << GetLastError();
return 1; // quit if we couldn't set the current directory
}
std::cout << "Set current directory to " << newDir << '\n';
// Delete some files
DeleteFile("file1.txt");
DeleteFile("bin\\file2.exe");
DeleteFile(R"(data\things\other\file3.zip)");
// Reset the current directory back to what it was.
if (!SetCurrentDirectory(oldDir)) {
std::cerr << "Error resetting current directory: #" << GetLastError();
return 1;
}
std::cout << "Reset current directory. \n";
// ...
return 0;
}
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.
The directory at the end of the active path is called the current directory; it is the directory in which the active application started, unless it has been explicitly changed. An application can determine which directory is current by calling the GetCurrentDirectory function. It is sometimes necessary to use the GetFullPathName function to ensure the drive letter is included if the application requires it.
Note Although each process can have only one current directory, if the application switches volumes by using the SetCurrentDirectory function, the system remembers the last current path for each volume (drive letter). This behavior will manifest itself only when specifying a drive letter without a fully qualified path when changing the current directory point of reference to a different volume. This applies to either Get or Set operations.
An application can change the current directory by calling the SetCurrentDirectory function.
The following example demonstrates the use of GetCurrentDirectory and SetCurrentDirectory.