gpt4 book ai didi

c++ - libssh2 - 使用 SFTP 读取文件

转载 作者:行者123 更新时间:2023-11-28 05:05:12 26 4
gpt4 key购买 nike

我正在使用 libssh2 库与设备建立 SFTP session 。

但是当我尝试读取文件并返回输出时,永远不会返回完整的文件。

我认为是因为文件中间的控制字符(如 \0)。

代码:

sftp_handle = libssh2_sftp_open(sftp_session, filename, LIBSSH2_FXF_READ, 0);
if (!sftp_handle) return "-1";
char buf[99999];
int x = libssh2_sftp_read(sftp_handle, buf, sizeof(buf));
char * output = (char *)malloc(sizeof(char)*x);
memcpy(output, buf, x);
output[x] = '\0';
libssh2_sftp_close(sftp_handle);

************更新 1************

我要读取的文件是一个包含几乎所有 ascii 字符的文本文件。

************更新 2************

x 是写入缓冲区的字节数,文件有 ~98kb(99999 字节)但 libssh2_sftp_read 函数返回 30000 到 x.

最佳答案

我假设代码只是片段,因此如果有一个围绕基本片段的循环,下面的评论可能不合适。

libssh2_sftp_read() 可能无法读取文件的全部字节,但它可以在单次调用中读取最大字节数。因此,可能需要重复此调用,直到它返回零或扫描读取缓冲区以检查 EOF 字符。 [EOF 检查可能使您的代码依赖于平台]。只需突出显示下面的手册页。

Reads a block of data from an LIBSSH2_SFTP_HANDLE. This method is modelled after the POSIX read(2) function and uses the same calling semantics. libssh2_sftp_read, will attempt to read as much as possible however it may not fill all of buffer if the file pointer reaches the end or if further reads would cause the socket to block.

关于c++ - libssh2 - 使用 SFTP 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44998756/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com