Skip to content

Instantly share code, notes, and snippets.

@evaporei
Created April 26, 2025 00:40
Show Gist options
  • Save evaporei/cf7e0eb0e871cdc585fde11d317fb922 to your computer and use it in GitHub Desktop.
Save evaporei/cf7e0eb0e871cdc585fde11d317fb922 to your computer and use it in GitHub Desktop.
List all entries of dir using win32
#include <windows.h>
#include <stdio.h>
int main() {
WIN32_FIND_DATA findFileData;
HANDLE hFind = INVALID_HANDLE_VALUE;
LPCSTR directoryPath = "C:\\Users\\myusername\\Downloads\\*";
hFind = FindFirstFile(directoryPath, &findFileData);
if (hFind == INVALID_HANDLE_VALUE) {
printf("FindFirstFile failed (%lu)\n", GetLastError());
return 1;
}
do {
printf("%s\n", findFileData.cFileName);
} while (FindNextFile(hFind, &findFileData) != 0);
FindClose(hFind);
return 0;
}
@evaporei
Copy link
Author

same but in Odin:

package standalone

import win32 "core:sys/windows"
import "core:strings"
import "core:fmt"
import "core:os"

main :: proc() {
    find_file_data: win32.WIN32_FIND_DATAW
    h_find := win32.INVALID_HANDLE_VALUE

    c_dir_path := win32.L("C:\\Users\\evaporei\\Downloads\\*")

    h_find = win32.FindFirstFileW(c_dir_path, &find_file_data)
    if h_find == win32.INVALID_HANDLE_VALUE {
        fmt.eprintln("FindFirstFile failed", win32.GetLastError())
        os.exit(1)
    }
    for {
        i := 0
        for find_file_data.cFileName[i] != 0 {
            fmt.print(rune(find_file_data.cFileName[i]))
            i += 1
        }
        fmt.println("")
        if win32.FindNextFileW(h_find, &find_file_data) == transmute(win32.BOOL)i32(0) do break;
    }
    win32.FindClose(h_find)
}

@evaporei
Copy link
Author

evaporei commented Apr 26, 2025

how to make it if your string ain't constant:

    s := "C:\\Users\\evaporei\\*"
    l := make([]u16, len(s) + 1)
    for ch, i in s {
        l[i] = u16(ch)
    }
    l[len(l) - 1] = 0

    h_find = win32.FindFirstFileW(raw_data(l), &find_file_data)

Edit: oh I just found out there's a bunch of wide string utils here.

So the above can be achieved like:

    s: cstring = "C:\\Users\\evaporei\\*"
    w_s := win32.utf8_to_utf16(string(s), context.temp_allocator)
    h_find = win32.FindFirstFileW(raw_data(w_s), &find_file_data)
    delete(w_s, context.temp_allocator)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment