【发布时间】:2019-04-13 03:43:30
【问题描述】:
我有一个 C++ 程序,它最终根据用户输入的索引打印目录路径。
#include <iostream>
using std::cout;
using std::cin;
int main() {
//SUB-ROUTINE: print directory paths with index, using "complex" algorithm
// (so an external command rather than a bash function)
// (this sub-routine gives choose-able options to a user)
// (please note this sub-routine includes `cout`)
unsigned index;
cout << "Input index: ";
cin >> index;
switch (index) {
case 0:
cout << "/home/user/foo"; break;
case 1:
cout << "/home/user/bar"; break;
default:
cout << "/home/user";
}
}
但是你不能用 bash 写
cd $(a.out)
因为很多原因。原因之一是a.out 的输出不仅仅是结果目录路径。
在这种情况下,如何更改调用进程的当前目录(bash)? Linux特定的方式是可以的。当然,将目录路径输出到文件(在 ramdisk 中)并从 bash 中读取它可以实现我想要的,但我认为这不是一个明智的方法。
相关:Changing the directory of the shell through a C++ program
补充:
如果我将 C++ 程序重写为
#include <iostream>
using std::cout;
using std::cin;
int main(int argc, char **argv) {
if (argc == 1) {
//print directory paths with index
} else {
unsigned index = atoi(argv[1]);
switch (index) {
case 0:
cout << "/home/user/foo"; break;
case 1:
cout << "/home/user/bar"; break;
default:
cout << "/home/user";
}
}
}
,那我就可以写了
./a.out
reply -p "Input index: "
cd $(a.out $REPLY)
但这并不简单(脏)并且使程序更加复杂。
【问题讨论】: