19

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

Charles Sprayberry
  • 7,741
  • 3
  • 41
  • 50
Biswajyoti Das
  • 7,881
  • 11
  • 34
  • 26

6 Answers6

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
  • 1
    Thanks Peter, so it seems that the physical change of directory will not take place . – Biswajyoti Das Aug 18 '09 at 13:10
  • 2
    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 Aug 18 '09 at 13:23
  • 7
    And 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);

See the recent POSIX documentation for chdir() is here.

alk
  • 69,737
  • 10
  • 105
  • 255
Dmitry Brant
  • 7,612
  • 2
  • 29
  • 47
3

Yes, the chdir() function.

Jesper
  • 202,709
  • 46
  • 318
  • 350
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