programmatically change directory in UNIX

V

Varun Yagain

hi,
please do let me know how i can change the directory through my
program and retain it too after i exit; if there's a way to do it.
regards,
varun yagain.
 
T

Tobias Oed

Varun said:
hi,
please do let me know how i can change the directory through my
program and retain it too after i exit; if there's a way to do it.
regards,
varun yagain.

This question is not apropriate for clc. comp.unix.programmer is a better
place.

<OT>
You can't. That's why cd has to be shell builtin and not an external
command.
<\OT>

Tobias
 
L

Lew Pitcher

hi,
please do let me know how i can change the directory through my
program and retain it too after i exit; if there's a way to do it.
regards,

First off, this is off-topic for C.L.C

2nd, look at the chdir(2) function for the Unix way to "change directories"

3rd. You aren't going to be able to retain the new directory after you exit.
That's not how Unix works.


--
Lew Pitcher
IT Consultant, Enterprise Technology Solutions
Toronto Dominion Bank Financial Group

(Opinions expressed are my own, not my employers')
 
D

Dan Pop

In said:
please do let me know how i can change the directory through my
program and retain it too after i exit; if there's a way to do it.

The current working directory is a property of the program. It is
not passed back to the "parent" process, so this piece of information
is normally lost when the program terminates.

It is always possible to do something about it, just don't expect it
to happen by magic:

fangorn:~/tmp 1921> pwd
/afs/ifh.de/user/d/danpop/tmp
fangorn:~/tmp 1922> cat test.c
#include <stdio.h>
#include <unistd.h>

char buff[FILENAME_MAX];

int main()
{
chdir("/usr/bin");
if (getcwd(buff, sizeof buff) != NULL) puts(buff);
else puts("unknown");
return 0;
}
fangorn:~/tmp 1923> gcc test.c
fangorn:~/tmp 1924> cd `./a.out`
fangorn:/usr/bin 1925> pwd
/usr/bin

Of course, this approach works only as long as you don't use stdout for
any other purposes...

Dan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top