Stream example with IPWorks SSH & SFTP

The C++ editions of IPWorks SSH & IPWorks SFTP are able to use streams for transferring files. This is done by implementing an abstract class (a.k.a. making it concrete). For details on the interface refer to the documentation. Below is an implementation that reads only.

#include #include #include #include "include/ipworkssftp.h"; using namespace std; const char* fileData = "hello world.\0"; // Our stream will support reading, but not seeking or writing. class SftpReadStream : public IPWorksSFTPStream { int pos = 0; int len = strlen(fileData); int readBytes = 0; public: // properties bool CanRead() { return true; } bool CanSeek() { return false; // Seeking is not supported. } bool CanWrite() { return false; // Writing is not supported. } int64 GetLength() { return len; } // methods void Close() { pos = 0; readBytes = 0; } int Flush() { pos = 0; readBytes = 0; return 0; } int Read(void* buffer, int count) { readBytes = 0; char* out = (char*)buffer; while (pos < len && readBytes < count) { out[pos] = fileData[pos]; readBytes++; pos++; } return readBytes; } int64 Seek(int64 offset, int seekOrigin) { // MUST always be able to get current pos even if seeking is not supported. if (offset == 0 && seekOrigin == 1) return pos; return -1; } int Write(const void* buffer, int count) { return -1; // Writing is not supported. } }; class SftpClient : public SFTP { public: virtual int FireSSHServerAuthentication(SFTPSSHServerAuthenticationEventParams* e) { printf("Connecting to server. [%s] is the fingerprint of the hostkey. Accepting.\n", e->Fingerprint); e->Accept = true; return 0; } }; int main() { SftpClient client; SftpReadStream inputStream; client.SetSSHUser("YourUser"); client.SetSSHPassword("YourPassword"); client.SSHLogon("sftp.server.com", 22); if (client.GetLastErrorCode()) goto done; client.SetUploadStream(&inputStream); client.SetRemoteFile("helloworld.txt"); client.Upload(); if (client.GetLastErrorCode()) goto done; client.SSHLogoff(); if (client.GetLastErrorCode()) goto done; done: if (client.GetLastErrorCode()) { printf("Error: [%i] %s\n", client.GetLastErrorCode(), client.GetLastError()); } printf("done.\n"); getchar(); return 0; }

We appreciate your feedback.  If you have any questions, comments, or suggestions about this article please contact our support team at kb@nsoftware.com.