views:

583

answers:

5

Is there any way by which I can change to any directory by executing a C program?

+1  A: 

The chdir() function (for more info, man chdir).

Michael Foukarakis
+1  A: 

Yes, the chdir() function.

Jesper
+1  A: 

Well, the POSIX command for changing the current directory is:

chdir(const char*path);
Dmitry Brant
+1  A: 
#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
+4  A: 

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.

Peter van der Heijden
Thanks Peter, so it seems that the physical change of directory will not take place .
Biswajyoti Das
The 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
And this is why 'cd' is a shell builtin, not a separate executable.
Greg Rogers