Delphi DLL
Delphi DLL
Detect End-of-File on a Remote SFTP File
See more SFTP Examples
Demonstrates the Chilkat SFtp.Eof method, which returns whether the most recent read for a handle received the SFTP end-of-file status. The only argument is the handle. This example reads until Eof is true.
Background: The timing here is worth understanding: reading exactly through the final byte does not immediately set EOF. The next read succeeds, returns zero bytes, sets the status to
SSH_FX_EOF, and only then does Eof report true. That is why the loop tests Eof after each read rather than assuming a short read means the end — a short read can also just be the server returning less than requested.Chilkat Delphi DLL Downloads
var
success: Boolean;
sftp: HCkSFtp;
port: Integer;
password: PWideChar;
handle: PWideChar;
sbContent: HCkStringBuilder;
chunkSize: Integer;
reading: Boolean;
chunk: PWideChar;
begin
success := False;
// Demonstrates the SFtp.Eof method, which returns whether the most recent read for a handle
// received the SFTP end-of-file status. The only argument is the handle.
sftp := CkSFtp_Create();
// Connect, authenticate, and initialize the SFTP subsystem.
port := 22;
success := CkSFtp_Connect(sftp,'sftp.example.com',port);
if (success = False) then
begin
Memo1.Lines.Add(CkSFtp__lastErrorText(sftp));
Exit;
end;
// 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) then
begin
Memo1.Lines.Add(CkSFtp__lastErrorText(sftp));
Exit;
end;
success := CkSFtp_InitializeSftp(sftp);
if (success = False) then
begin
Memo1.Lines.Add(CkSFtp__lastErrorText(sftp));
Exit;
end;
handle := CkSFtp__openFile(sftp,'subdir/data.txt','readOnly','openExisting');
if (CkSFtp_getLastMethodSuccess(sftp) = False) then
begin
Memo1.Lines.Add(CkSFtp__lastErrorText(sftp));
Exit;
end;
// Read until Eof reports the end of the file. Note that reading exactly through the final byte
// does not set EOF; the next read returns zero bytes and then Eof becomes true.
sbContent := CkStringBuilder_Create();
chunkSize := 4096;
reading := True;
while reading do
begin
chunk := CkSFtp__readFileText(sftp,handle,chunkSize,'utf-8');
if (CkSFtp_LastReadFailed(sftp,handle)) then
begin
Memo1.Lines.Add(CkSFtp__lastErrorText(sftp));
Exit;
end;
CkStringBuilder_Append(sbContent,chunk);
reading := not CkSFtp_Eof(sftp,handle);
end;
success := CkSFtp_CloseHandle(sftp,handle);
if (success = False) then
begin
Memo1.Lines.Add(CkSFtp__lastErrorText(sftp));
Exit;
end;
Memo1.Lines.Add(CkStringBuilder__getAsString(sbContent));
CkSFtp_Disconnect(sftp);
CkSFtp_Dispose(sftp);
CkStringBuilder_Dispose(sbContent);