#include <windows.h>
#include <commdlg.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
    WCHAR file[MAX_PATH] = {0};

    OPENFILENAMEW ofn = {
        .lStructSize = sizeof(ofn),
        .lpstrFilter = L"Text Files\0*.txt\0All Files\0*.*\0",
        .lpstrFile = file,
        .nMaxFile = MAX_PATH,
        .lpstrTitle = L"Select File to Write To",
        .Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST
    };

    int res = GetOpenFileNameW(&ofn);

    if (!res) {
        _putws(L"File selection cancelled or failed!");
        exit(1);
    }

    FILE *f = _wfopen(ofn.lpstrFile, L"w");
    if (!f) {
        _wperror(L"Error opening file for writing");
        exit(1);
    }

    if (fwprintf(f, L"foo") < 0) {
        _wperror(L"Error writing to file");
        fclose(f);
        exit(1);
    } else {
        wprintf(L"Successfully wrote \"foo\" to '%s'.\n", ofn.lpstrFile);
    }

    fclose(f);

    return 0;
}
