Current Working Directory in Windows Console Programs

Pursuant to an argument at this Super User question, I have done some testing and written a test program to try to clarify the situation with current-working-directories.

As Raymond Chen explains, per-drive CWDs have been around since DOS, which makes sense because DOS’s only interface was the command-line. He goes on to explain that in Windows, the command prompt keeps track of per-drive CWDs by using environment variables.

The point is that while the actual manner in which they are tracked may differ, there are per-drive CWDs in all Microsoft operating systems from DOS, up to Windows 7. This can be easily demonstrated with the following program (adjusting drive letters and paths as appropriate).

#include	
#include	
#include	

void PrintCWDs() {
	char cwd[260]="";
	for (int i=3; i<27; i++) {
		if (!_chdrive(i)) {
			getcwd(cwd,260);
			printf("  %c: = %s\n", 64+i, cwd);
		}
	}
	printf("Press a key...\n");
	char key=getch();
}

void ChangeCWDs() {
	for (int i=3; i<27; i++) {
		if (!_chdrive(i)) {
			switch (i) {
				case 'C'-'A'+1	:chdir("\\Windows\\System32\\Drivers");		break;
				case 'H'-'A'+1	:chdir("\\Temp\\Chromium\\Cache");			break;
				case 'K'-'A'+1	:chdir("\\Data\\eMail\\OE");				break;
				case 'P'-'A'+1	:chdir("\\Videos\\Commercials");			break;
				case 'T'-'A'+1	:chdir("\\Program Files\\Common Files");	break;
			}
		}
	}
}

int main(int argc, char**argv) {
	printf("\nOriginal CWDs:\n");
	PrintCWDs();
	printf("\nChanging CWDs...\n");
	ChangeCWDs();
	printf("\nNew CWDs:\n");
	PrintCWDs();
	printf("\nAnd again:\n");
	PrintCWDs();

	return 0;
}

This program shows that the CWD is maintained for each drive in DOS, Windows XP, and Windows 7 as seen below.

DOS:

CWDTest run in DOS without NTFS support.

CWDTest run in DOS with NTFS support.

XP:

CWDTest run in XP from the command-prompt.

CWDTest run in XP from the desktop or an Explorer folder.

CWDTest run in XP from the Run dialog.

7:

CWDTest run in 7 from the command-prompt.

CWDTest run in 7 from the desktop or an Explorer folder.

CWDTest run in XP from the Run dialog.

Leave a Reply

Your email address will not be published. Required fields are marked *

one + 2 =