Sample code for 30+ languages & platforms
C

Rename or Move a Remote File or Directory

See more SFTP Examples

Demonstrates the Chilkat SFtp.RenameFileOrDir method, which renames or moves a remote file or directory. The first argument is the old path and the second is the new path.

Background: Rename and move are the same operation in SFTP: changing only the final path component renames in place, while changing the directory portion relocates the item. When source and destination are on the same filesystem the server does this as a fast metadata change rather than copying data, which is why moving even a large file is near-instant. Moving across filesystems, or onto an existing target, may fail depending on the server.

Chilkat C Downloads

C
#include <C_CkSFtp.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkSFtp sftp;
    int port;
    const char *password;

    success = FALSE;

    //  Demonstrates the SFtp.RenameFileOrDir method, which renames or moves a remote file or
    //  directory.  The 1st argument is the old path and the 2nd is the new path.

    sftp = CkSFtp_Create();

    //  Connect, authenticate, and initialize the SFTP subsystem.
    port = 22;
    success = CkSFtp_Connect(sftp,"sftp.example.com",port);
    if (success == FALSE) {
        printf("%s\n",CkSFtp_lastErrorText(sftp));
        CkSFtp_Dispose(sftp);
        return;
    }

    //  Normally you would not hard-code the password in source.  You should instead obtain it
    //  from an interactive prompt, environment variable, or a secrets vault.
    password = "mySshPassword";

    success = CkSFtp_AuthenticatePw(sftp,"mySshLogin",password);
    if (success == FALSE) {
        printf("%s\n",CkSFtp_lastErrorText(sftp));
        CkSFtp_Dispose(sftp);
        return;
    }

    success = CkSFtp_InitializeSftp(sftp);
    if (success == FALSE) {
        printf("%s\n",CkSFtp_lastErrorText(sftp));
        CkSFtp_Dispose(sftp);
        return;
    }

    //  Rename a file within the same directory.
    success = CkSFtp_RenameFileOrDir(sftp,"subdir/report.txt","subdir/report_final.txt");
    if (success == FALSE) {
        printf("%s\n",CkSFtp_lastErrorText(sftp));
        CkSFtp_Dispose(sftp);
        return;
    }

    //  Because rename can also move, the same method relocates an item to a different directory.
    success = CkSFtp_RenameFileOrDir(sftp,"subdir/report_final.txt","archive/report_final.txt");
    if (success == FALSE) {
        printf("%s\n",CkSFtp_lastErrorText(sftp));
        CkSFtp_Dispose(sftp);
        return;
    }

    printf("Renamed and moved.\n");

    CkSFtp_Disconnect(sftp);


    CkSFtp_Dispose(sftp);

    }