繁体   English   中英

C++:Output 中的不需要的字符

[英]C++: Unwanted Character in Output

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

示例 output 用于命令 "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, buffer, sizeof(buffer), 0);
}

这是我的 function。

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, buffer, sizeof(buffer), 0);
    while (nbytes > 0)
    {
        output.append(buffer, sizeof(buffer));
        nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 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;
}

sizeof(buffer)表示sizeof(char*)可能是 4 个字节。 ssh_channel_read第三个参数(计数)是你的缓冲区的限制。 不是缓冲区中加载的元素数量。 您将其作为返回值。 所以首先,你需要为你的缓冲区分配一些 memory,比如说 256 字节:

const int BUFFER_SIZE = 256;
char buffer[BUFFER_SIZE];

现在您可以将缓冲区大小作为参数传递并填充缓冲区:

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

你需要 append 和你读到的nbytes一样多。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM