Is there any way by which I can change to any directory by executing a C program?
Asked
Active
Viewed 8.2k times
19
-
Are you looking for `cd`? Or are you looking for a way to actually set an active directory in C? – Eric Aug 18 '09 at 12:58
-
2It's called a hammer! :P – Mr. Smith Aug 18 '09 at 13:00
-
This questions is often given as an exercise to students leaning unix-like OSs. If that is the case, pay careful attention to what Peter says about *which processes* can and can not be affected. – dmckee --- ex-moderator kitten Aug 18 '09 at 15:22
6 Answers
21
The chdir()
function. For more info, use man chdir
.

Zach Saucier
- 24,871
- 12
- 85
- 147

Michael Foukarakis
- 39,737
- 6
- 87
- 123
13
Depending on your OS there are different calls for changing the current directory. These will normally only change the current dir of the process running the executable. After the process exits you will be in the directory you started in.

heijp06
- 11,558
- 1
- 40
- 60
-
1Thanks Peter, so it seems that the physical change of directory will not take place . – Biswajyoti Das Aug 18 '09 at 13:10
-
2The current directory is part of the state of a process (like open files, memory maps, environment variable...). Usually a process can't change the state of another process (usually, debugger and so on may have special privileges, but that is another story). – AProgrammer Aug 18 '09 at 13:23
-
7And this is why 'cd' is a shell builtin, not a separate executable. – Greg Rogers Aug 18 '09 at 13:25
-
There is a workaround, use [code] cd \`whateverProgramThatPrintsDirToStdout\` [/code] – neoedmund May 07 '19 at 05:41
12
chdir()
changes only the current working directory of the process but not of the context in which you are working. Suppose you execute a program in the terminal and your current directory is /home/Documents
, then on executing a program having the following lines
chdir("cd ../Downloads");
will not change the working directory of the terminal, but changes that of the process only.

agf
- 171,228
- 44
- 289
- 238

Santak Dalai
- 129
- 1
- 2
11
Well, the POSIX command for changing the current directory is:
chdir(const char*path);

alk
- 69,737
- 10
- 105
- 255

Dmitry Brant
- 7,612
- 2
- 29
- 47
0
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
system("C:\\windows\\notepad.exe");
chdir("C:\\windows\\desktop");
return 0;
}
As per this

Kevin Boyd
- 12,121
- 28
- 86
- 128