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

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

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

while (fin)
{
    constexpr size_t 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, "Error writing to file: %s\n", ssh_get_error(ssh_session));
            sftp_close(file);
            return 1;
        }
    }
}

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

  std::vector<char> buf(bufsize);        // allocate buffer
  fin.read(buf.data(), bufsize);         // read file contents into buffer

  sftp_write(file, buf.data(), bufsize); // write buffer 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.

Tags:

C++

C

Sftp

Ssh

Libssh