我需要使用libssh
和scp
协议从远程位置下载目录。该目录中包含音频,视频和一些文本文件。使用以下代码,我试图借助scp
函数从目录中libssh scp
这些文件,但是它正在下载一些垃圾文件。如果我尝试获取txt
文件,它会将数据复制到某个随机名称的文件中,例如dø
,oyø
,但在Windows计算机的给定路径中没有扩展名。谁能指导我做错了什么以及如何修复它以使文件传输?或者,是否还有其他方法可以使用libssh
下载这些文件?
#include <iostream>
#include <string>
#include <libssh.h>
#include <stdlib.h>
#include <fstream>
#include <stdio.h>
#include <fcntl.h>
#include <sstream>
#include <io.h>
static int fetch_files(ssh_session session)
{
int size;
int mode;
int rc;
int fd;
ssh_scp scp = ssh_scp_new(session,
SSH_SCP_READ | SSH_SCP_RECURSIVE,
"/data/misc/qmmf/snapshot_01.jpg");
if (scp == NULL)
{
std::cout << "Error allocating scp session: scp == NULL";
return -1;
}
rc = ssh_scp_init(scp);
if (rc != SSH_OK)
{
std::cout << "Error initializing scp session: rc != SSH_OK";
ssh_scp_free(scp);
return rc;
}
rc = ssh_scp_pull_request(scp);
if (rc != SSH_SCP_REQUEST_NEWFILE)
{
cout << "Error receiving information about file: rc != SSH_SCP_REQUEST_NEWFILE";
return -3;
}
int fileSize = ssh_scp_request_get_size(scp);
string filename = _strdup(ssh_scp_request_get_filename(scp));
int filePermission = ssh_scp_request_get_permissions(scp);
cout << "fileSize" << fileSize << endl;
cout << "filename" << filename << endl;
cout << "filePermission" << filePermission << endl;
char* buffer1 = (char *) malloc(sizeof(char) * fileSize);
if (buffer1 == NULL)
{
cout << "Memory allocation error!";
return SSH_ERROR;
}
ssh_scp_accept_request(scp);
rc = ssh_scp_read(scp, buffer1, sizeof(char) * fileSize);
if (rc == SSH_ERROR)
{
cout << "Error receiving file data: rc == SSH_ERROR!";
free(buffer1);
return rc;
}
char path[10000];
sprintf_s(path, "C:\Documents/%s", filename);
if (0 < (fd = open(path, O_RDWR | O_CREAT | O_TRUNC, filePermission)))
{
write(fd, buffer1, sizeof(char) * fileSize);
close(fd);
}
else
{
cout << "Failed to open file!";
}
return 0;
}