1

I am in the directory /home/destination I need to go back to the /home directory. Any ideas on how to implement this using a C-program?

Sergey K.
  • 24,894
  • 13
  • 106
  • 174
David
  • 13
  • 1
  • 1
  • 3
  • Are you looking for a C program that you can invoke from the command line and that sets the current directory? Or you want to set the current directory within the C program? – Giorgio Aug 17 '11 at 08:31
  • i need a c program running in the command line and changing the current directoy – David Aug 17 '11 at 08:41
  • What's wrong with using the shell's built-in `cd` command? – Wyzard Aug 18 '11 at 02:45

3 Answers3

5

You can use the chdir function for this:

chdir(".."); /* change current working directory, go one level up */
Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207
5

A program can only change its own environment. Thus, the program can chdir but it will not change the current directory of the parent. That's why cd can't be implemented as an external command.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • so there is no way to change the directory of the parent. we can only go forward and backward in the program's environment – David Aug 17 '11 at 08:44
1

If you'd like to go level up chdir(".."); will do the work. But if you'd like to have behaviour like cd - then you should use this code:

char *prev;
prev = getcwd(prev, 0); /*POSIX.1-2001: will malloc enough memory*/
/*fail if prev is NULL, do something*/
chdir(prev);
free(prev);
Maciej
  • 3,685
  • 1
  • 19
  • 14