如何从程序中更改 bash 目录C++
How can I change bash directory from C++ program?
我有一个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的方式是可以的。当然,将目录路径输出到一个文件(在虚拟硬盘中(并从bash读取它可以实现我想要什么,但我认为这不是一个明智的方法。
相关:通过C++程序更改 shell 的目录
补充:
如果我将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)
但这并不简单(肮脏(,并且使程序更加复杂。
选项 1
它有点重,但您可以使用
cd $(a.out | awk '{print $NF}')
选项 2
更改行
cout << "Input index: ";
自
cout << "Input index: n";
,然后使用
cd $(a.out | tail -1)
选项 3
删除行
cout << "Input index: ";
共并使用:
cd $(a.out)
选项 4
使用一些不同的标记打印所选目录,并使用它来过滤输出。
例:
std::cout << "==== " << "/home/user/foo" << std::endl;
break;
然后,在 bash
中,您可以使用:
cd $(a.out | grep '====' | awk '{print $2}]
我刚刚找到了答案。
据man bash
,
命令替换
(截图(
Bash 通过在子外壳环境中执行命令并将命令替换替换为命令的标准输出来执行扩展
因此,可以将所有cout
替换为最后一个(带有using std::cerr;
(以外的cerr
相关文章:
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 如何在c++中打印目录
- 递归列出所有目录中的C++与Python与Ruby的性能
- 递归计数给定目录的文件和所有目录
- 用MacOS Mojave编译C++:致命错误:mpi.h:没有这样的文件或目录
- VS2017,C++包含目录与附加包含目录,子文件夹包含失败-但为什么
- C++将目录中的所有文件与::filesystem进行比较
- 在C++中使用LZ4压缩目录
- 将bash参数传递给c++
- visual c++,如何获取解决方案目录中的代码
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 如何在文档文件夹中创建目录
- g++编译包含的头:没有这样的文件或目录
- 对于MacOS上的G++,如何添加默认的include目录/usr/local/include和默认的库搜索路径/usr
- 从源代码安装 gcc: bash: gcc -v /usr/bin/gcc: 是一个目录
- 如何从程序中更改 bash 目录C++
- 以目录作为参数运行C 文件?而是使用bash
- execve /bin /bash:h:没有这样的文件或目录
- 如何遍历当前目录并将文件存储在数组中?Bash 外壳脚本
- -bash ./foo:编译后没有这样的文件或目录