Sample code for 30+ languages & platforms
Zig

Get Number of FIles in Directory, not including sub-directories

See more FTP Examples

_LANGUAGE_ example demonstrating how to get the number of files in a directory not including sub-directories.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    const ftp = try chilkat.Ftp2.init();
    defer ftp.deinit();

    ftp.setHostname("ftp.example.com");
    ftp.setUsername("login");
    ftp.setPassword("password");

    // Connect and login to the FTP server.
    ftp.connect() catch {
        std.debug.print("{s}\n", .{try ftp.getLastErrorText(alloc)});
        return;
    };

    // The ListPattern property is our directory listing filter.
    // The default value is "*", which includes everything.
    std.debug.print("{s}\n", .{try ftp.getListPattern(alloc)});

    // Fetch the current remote directory contents by
    // calling GetDirCount
    var i: i32 = 0;
    const n = ftp.getDirCount();
    if (n < 0) {
        std.debug.print("{s}\n", .{try ftp.getLastErrorText(alloc)});
        return;
    }

    if (n > 0) {
        // Loop over the directory contents, incrementing the count
        // each time it is NOT a directory.
        var file_count: i32 = 0;
        i = 0;
        while (i < n) : (i += 1) {
            // Is this NOT a sub-directory?
            if (!ftp.getIsDirectory(i)) {
                file_count = file_count + 1;
                // Display the filename
                std.debug.print("{s}\n", .{try ftp.getFilename(alloc, i)});
            }
        }

        std.debug.print("Total number of files = {d}\n", .{file_count});
    }

    try ftp.disconnect();
}