Sample code for 30+ languages & platforms
Zig

Directory Existence Check

See more FTP Examples

How to test if a directory exists on an FTP server.

A good way to check to see if a directory already exists is to try to "cd" to that remote directory by calling ChangeRemoteDir. If it succeeds, then the directory exists. If not, then it does not exist. An alternative method is to set the ListPattern = "*" and then iterate over the files/directories, looking for the directory.

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;
    };

    // Does the "temp" directory exist?
    if (ftp.changeRemoteDir("/temp")) {
        std.debug.print("Yes, the temp directory exists.\n", .{});
        //  Yes, it exists. Restore the current remote dir:
        ftp.changeRemoteDir("..") catch {
            std.debug.print("{s}\n", .{try ftp.getLastErrorText(alloc)});
            return;
        };
    } else |_| {}

    // Alternatively, you may set the ListPattern = "*" and
    //  look for the directory:
    ftp.setListPattern("*");

    var i: i32 = 0;
    const n = ftp.getDirCount();
    if (n < 0) {
        // Failed to get directory listing based on ListPattern
        std.debug.print("{s}\n", .{try ftp.getLastErrorText(alloc)});
        return;
    }

    if (n > 0) {
        i = 0;
        while (i < n) : (i += 1) {
            const is_dir = ftp.getIsDirectory(i);
            if (is_dir) {
                const fname = try ftp.getFilename(alloc, i);
                if (std.mem.eql(u8, fname, "temp")) {
                    std.debug.print("Found temp directory!\n", .{});
                    try ftp.disconnect();
                    return;
                }
            }
        }
    }

    try ftp.disconnect();
}