shell_expand

昨日作ったlaunch_shell()のラッパーとして、シェルのコマンド展開のような働きをする関数を追加しました。
実装はこんな感じです。

std::string shell_expand(const std::string& cmd)
{
    // 標準出力のみパイプで受け取る
    context ctx;
    ctx.stdout_behavior(capture_stream());

    child c = launch_shell(cmd, ctx);

    pipe_source& src = c.stdout_source();

    // shell_expand_filterで整形してバッファに出力する
    std::string buf;
    io::copy(
        io::compose(detail::shell_expand_filter(), src),
        io::back_inserter(buf)
    );

    c.wait();

    return buf;
}

これで

// hoge.txtの1行目をsに代入
std::string s = shell_expand("head -n 1 hoge.txt");

のようなことができます。
もちろんプロセスを起動する分遅いですが、スクリプト言語並に簡単に子プロセスを起動して出力を得ることが出来ます。


現在のshell_expand_filterは改行を全て空白に置き換えていますが、実際のシェルでは末尾の改行を削るだけみたいなので、他の似た実装を参考に調整中です。