How to copy a file in C/C++ with libssh and sftp

天大地大妈咪最大 提交于 2019-11-30 14:46:56

Open the file in the usual way (using C++'s fstream or C's stdio.h), read its contents to a buffer, and pass the buffer to sftp_write.

Something like this:

ifstream fin("file.doc", ios::binary);
if (fin) {
  fin.seekg(0, ios::end);
  ios::pos_type bufsize = fin.tellg(); // get file size in bytes
  fin.seekg(0); // rewind to beginning of file

  char* buf = new char[bufsize];
  fin.read(buf, bufsize); // read file contents into buffer

  sftp_write(file, buf, bufsize); // write to remote file
}

Note that this is a very simple implementation. You should probably open the remote file in append mode, then write the data in chunks instead of sending single huge blob of data.

The following example uses ifstream in a loop, to void loading a whole file into a memory (what the accepted answer does):

ifstream fin("C:\\myfile.zip", ios::binary);

while (fin)
{
    #define MAX_XFER_BUF_SIZE 10240
    char buffer[MAX_XFER_BUF_SIZE];
    fin.read(buffer, sizeof(buffer));
    if (fin.gcount() > 0)
    {
        ssize_t nwritten = sftp_write(NULL, buffer, fin.gcount());
        if (nwritten != fin.gcount())
        {
            fprintf(stderr, "Can't write data to file: %s\n", ssh_get_error(ssh_session));
            sftp_close(file);
            return 1;
        }
    }
}
alvin chew

I used followed the example here.

sftp_read_sync uses an infinite loop to read a file from a server into /path/to/profile from server path /etc/profile.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!