簡體   English   中英

如何從C ++程序更改bash目錄?

[英]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的方式是可以的。 當然,當然,將目錄路徑輸出到文件(在ramdisk中)並從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通過在子shell環境中執行命令並使用命令的標准輸出替換命令替換來執行擴展

因此,除了最后一個cerr之外,可以用cerr替換所有coutusing std::cerr; )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM