C++:输出中不需要的字符

问题描述

我正在使用 libssh,我想从执行的命令中获取一些输出。它在大多数情况下都有效,但我在输出中得到了不需要的字符。我做错了什么?

命令“test -f”/path/to/file“&& echo found || echo not found”的示例输出

not found
t foun

我想要“未找到”,而不是它下面的那一行——“t foun”

我认为问题出在哪里:

nbytes = ssh_channel_read(channel,buffer,sizeof(buffer),0);
while (nbytes > 0)
{
    output.append(buffer,sizeof(buffer));
    nbytes = ssh_channel_read(channel,0);
}

这是我的函数。

std::string exec_command(ssh_session session,const std::string& command)
{
    ssh_channel channel;
    int rc;
    char* buffer;
    std::string output;
    int nbytes;

    channel = ssh_channel_new(ssh_session);
    if (channel == NULL)
        return "Error";

    rc = ssh_channel_open_session(channel);
    if (rc != SSH_OK)
    {
        ssh_channel_free(channel);
        return "Not Ok";
    }

    rc = ssh_channel_request_exec(channel,command.c_str());
    if (rc != SSH_OK)
    {
        ssh_channel_close(channel);
        ssh_channel_free(channel);
        return "Not Ok";
    }

    nbytes = ssh_channel_read(channel,0);
    while (nbytes > 0)
    {
        output.append(buffer,sizeof(buffer));
        nbytes = ssh_channel_read(channel,0);
    }

    if (nbytes < 0)
    {
        ssh_channel_close(channel);
        ssh_channel_free(channel);
        return "Error";
    }

    ssh_channel_send_eof(channel);
    ssh_channel_close(channel);
    ssh_channel_free(channel);

    return output;
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)