Is there anyway to download file or folder from server using SFTP? (C++, libssh)
I try to follow example here: https://github.com/substack/libssh/blob/master/examples/samplesftp.c
But I cannot download file/folder...
Here is my code:
int AutoUpdator::sftp_read_sync(ssh_session session, sftp_session sftp, std::string path)
{
ans_info("start sftp_read_sync");
std::cout << path << std::endl;
int access_type;
sftp_file file;
char buffer[MAX_XFER_BUF_SIZE];
int nbytes, nwritten, rc;
int fd;
access_type = O_RDONLY;
file = sftp_open(sftp, path.c_str(), access_type, 0);
if (file == NULL) {
fprintf(stderr, "Can't open file for reading: %s\n", ssh_get_error(session));
return SSH_ERROR;
}
/* open a file for writing... */
fd = open("/home/writing_test.txt",O_WRONLY|O_CREAT, 0700);
if (fd < 0) {
fprintf(stderr, "Can't open file for writing: %s\n", strerror(errno));
return SSH_ERROR;
}
for (;;) {
nbytes = sftp_read(file, buffer, sizeof(buffer));
if (nbytes > 0) {
std::cout << "nbytes :" << nbytes << std::endl;
std::cout << "buffer :" << buffer << std::endl;
server_version_ = buffer;
ans_info("server_version : " + server_version_);
}
else if (nbytes == 0) {
ans_info("EOF");
break; // EOF
}
else if (nbytes < 0) {
fprintf(stderr, "Error while reading file: %s\n", ssh_get_error(session));
sftp_close(file);
return SSH_ERROR;
}
nwritten = write(fd, buffer, nbytes);
if (nwritten != nbytes) {
fprintf(stderr, "Error writing: %s\n", strerror(errno));
sftp_close(file);
return SSH_ERROR;
}
}
rc = sftp_close(file);
if (rc != SSH_OK) {
fprintf(stderr, "Can't close the read file: %s\n", ssh_get_error(session));
return rc;
}
return SSH_OK;
}
In this way, I can copy a text file. More precisely, it seems to be a way to copy text content and then add it to a new text file in the local folder.
I want to download some files from server. If I can get it using sftp, it is the best way. But if there's any other useful way, can you let me know?