C
C
Count Files in a Remote FTP Directory
See more FTP Examples
Demonstrates the Chilkat Ftp2.GetDirCount method, which returns the number of files and directories in the current remote directory. It takes no arguments; the first call retrieves the listing, and the count reflects the case-insensitive ListPattern filter. A negative return indicates failure.
Background:
GetDirCount is the entry point to Chilkat's index-based directory API: its first call fetches the listing for the current directory into a cache, and the returned count establishes the valid index range (0 through count - 1) for the accessor methods that read names, sizes, and attributes. The ListPattern property narrows the listing to matching names before counting, which is how you list, say, only *.html without filtering in your own code.Chilkat C Downloads
#include <C_CkFtp2.h>
void ChilkatSample(void)
{
BOOL success;
HCkFtp2 ftp;
int n;
int i;
const char *name;
success = FALSE;
// Demonstrates the Ftp2.GetDirCount method, which returns the number of files and directories in
// the current remote directory's listing. It takes no arguments. The first call retrieves the
// listing; the count reflects the case-insensitive ListPattern filter.
ftp = CkFtp2_Create();
CkFtp2_putHostname(ftp,"ftp.example.com");
CkFtp2_putUsername(ftp,"myFtpLogin");
// 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.
CkFtp2_putPassword(ftp,"myPassword");
success = CkFtp2_Connect(ftp);
if (success == FALSE) {
printf("%s\n",CkFtp2_lastErrorText(ftp));
CkFtp2_Dispose(ftp);
return;
}
success = CkFtp2_ChangeRemoteDir(ftp,"public_html");
if (success == FALSE) {
printf("%s\n",CkFtp2_lastErrorText(ftp));
CkFtp2_Dispose(ftp);
return;
}
// Optionally filter the listing with a wildcard pattern. "*" (the default) matches everything.
CkFtp2_putListPattern(ftp,"*.html");
n = CkFtp2_GetDirCount(ftp);
if (n < 0) {
printf("%s\n",CkFtp2_lastErrorText(ftp));
CkFtp2_Dispose(ftp);
return;
}
printf("Matching entries: %d\n",n);
// The count defines the valid index range 0 through n-1 for the indexed accessor methods.
for (i = 0; i <= n - 1; i++) {
name = CkFtp2_getFilename(ftp,i);
printf("%s\n",name);
}
success = CkFtp2_Disconnect(ftp);
if (success == FALSE) {
printf("%s\n",CkFtp2_lastErrorText(ftp));
CkFtp2_Dispose(ftp);
return;
}
CkFtp2_Dispose(ftp);
}