Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Change working Directory from User Input

I'm designing a mock shell program, and I can't quite mimic the "cd" command. I've tried chdir(), but that wasn't working, so I moved on to trying to change the environmental variable "PWD="

Here's what I have, and I think this may be close. (Please, please, correct me if I'm wrong or was closer with chdir())

else if (command == "cd")
        {
            string pathEnv = "PWD=";
            string newDir;
            cin >> newDir;
            pathEnv+=newDir;
            cout << pathEnv << endl;
            putenv(pathEnv.c_str());
        }

Hopefully the command would be 'cd /user/username/folder' and my pathEnv variable would be "PWD=/user/username/folder" which would maybe change the directory?

Any insight is greatly appreciated.

like image 540
twsmale Avatar asked Feb 20 '23 08:02

twsmale


2 Answers

chdir() should be the command you are looking for. Did you use getcwd() to fetch the current working directory after you set it?


Here is the code which worked for me.

#include <iostream>
#include <string>
#include <sys/param.h>
#include <unistd.h>

...

if (command == "curr") {
    char buffer[MAXPATHLEN];
    char *path = getcwd(buffer, MAXPATHLEN);
    if (!path) {
        // TODO: handle error. use errno to determine problem
    } else {
        string CurrentPath;
        CurrentPath = path;
        cout << CurrentPath << endl;
    }
} else if (command == "cd") {
    string newDir;
    cin >> newDir;
    int rc = chdir(newDir.c_str());
    if (rc < 0) {
        // TODO: handle error. use errno to determine problem
    }
}

There are three versions of getcwd():

char *getcwd(char *buf, size_t size);
char *getwd(char *buf);
char *get_current_dir_name(void);

please consult the man page in unix for details of usage.

like image 183
Jeffery Thomas Avatar answered Mar 08 '23 06:03

Jeffery Thomas


You'll always want to use system calls in your code and not "mock" up what the system may be doing such as changing PWD. If you are on a superior UNIX system you should use chdir or if on a Windows Box, the SetCurrentDirectory call. I'm not a Windows developer, whew, but I found this link. http://msdn.microsoft.com/en-us/library/windows/desktop/aa363806%28v=vs.85%29.aspx

like image 44
jiveturkey Avatar answered Mar 08 '23 05:03

jiveturkey