Skip to content

Commit 66aca5d

Browse files
committed
nob_write_entire_file
1 parent 5284171 commit 66aca5d

2 files changed

Lines changed: 40 additions & 0 deletions

File tree

nob.h

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2273,6 +2273,42 @@ NOBDEF bool nob_read_entire_dir(const char *parent, Nob_File_Paths *children)
22732273

22742274
NOBDEF bool nob_write_entire_file(const char *path, const void *data, size_t size)
22752275
{
2276+
#ifdef _WIN32
2277+
bool result;
2278+
HANDLE file;
2279+
size_t mark;
2280+
wchar_t *wide_path;
2281+
DWORD err;
2282+
BOOL b;
2283+
DWORD written;
2284+
2285+
result = true;
2286+
file = INVALID_HANDLE_VALUE;
2287+
mark = nob_temp_save();
2288+
wide_path = nob__unicode_utf8_to_unicode_utf16_temp(path);
2289+
file = CreateFileW(wide_path, GENERIC_WRITE, FILE_SHARE_DELETE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2290+
err = GetLastError();
2291+
nob_temp_rewind(mark);
2292+
if (file == INVALID_HANDLE_VALUE)
2293+
{
2294+
nob_log(NOB_ERROR, "Could not open file %s for writing: %s\n", path, nob_win32_error_message(err));
2295+
nob_return_defer(false);
2296+
}
2297+
b = WriteFile(file, data, (DWORD)size, &written, NULL);
2298+
if (!(b != FALSE && written == (DWORD)size))
2299+
{
2300+
err = GetLastError();
2301+
nob_log(NOB_ERROR, "Could not write into file %s: %s\n", path, nob_win32_error_message(err));
2302+
nob_return_defer(false);
2303+
}
2304+
defer:
2305+
if (file != INVALID_HANDLE_VALUE)
2306+
{
2307+
b = CloseHandle(file);
2308+
NOB_ASSERT(b != FALSE);
2309+
}
2310+
return result;
2311+
#else
22762312
bool result = true;
22772313

22782314
const char *buf = NULL;
@@ -2302,6 +2338,7 @@ NOBDEF bool nob_write_entire_file(const char *path, const void *data, size_t siz
23022338
defer:
23032339
if (f) fclose(f);
23042340
return result;
2341+
#endif // _WIN32
23052342
}
23062343

23072344
NOBDEF Nob_File_Type nob_get_file_type(const char *path)

tests/unicode.c

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,9 @@ static void test_unicode_utf8_file_operations(void)
8989
b = nob_rename(k_strings[(i + 1) % NOB_ARRAY_LEN(k_strings)], k_strings[i]);
9090
test(b);
9191

92+
b = nob_write_entire_file(k_strings[i], "test", 4);
93+
test(b);
94+
9295
b = nob_delete_file(k_strings[i]);
9396
test(b);
9497
}

0 commit comments

Comments
 (0)