tws*_*ale 4 c++ directory environment-variables c-str
我正在设计一个模拟shell程序,我无法完全模仿"cd"命令.我试过chdir(),但那不起作用,所以我继续试图改变环境变量"PWD ="
这就是我所拥有的,我认为这可能很接近.(如果我错了或与chdir()接近,请拜托,纠正我)
else if (command == "cd")
{
string pathEnv = "PWD=";
string newDir;
cin >> newDir;
pathEnv+=newDir;
cout << pathEnv << endl;
putenv(pathEnv.c_str());
}
Run Code Online (Sandbox Code Playgroud)
希望命令是'cd/user/username/folder',我的pathEnv变量将是"PWD =/user/username/folder",这可能会改变目录?
非常感谢任何见解.
chdir()应该是您正在寻找的命令.设置后,是否使用getcwd()获取当前工作目录?
这是适合我的代码.
#include <iostream>
#include <string>
#include <sys/param.h>
#include <unistd.h>
Run Code Online (Sandbox Code Playgroud)
...
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
}
}
Run Code Online (Sandbox Code Playgroud)
getcwd()有三个版本:
char *getcwd(char *buf, size_t size);
char *getwd(char *buf);
char *get_current_dir_name(void);
Run Code Online (Sandbox Code Playgroud)
有关使用的详细信息,请参阅unix手册页.
| 归档时间: |
|
| 查看次数: |
14026 次 |
| 最近记录: |