diff src/dirtools.c @ 10:42ac054c0231

*: huge refactoring dirtools now uses wchar (wayyy overdue) the timer doesn't have a stupid design anymore we don't use windows.h at all now ...
author Paper <paper@paper.us.eu.org>
date Sun, 11 Feb 2024 19:43:31 -0500
parents be4835547dd0
children e6a594f16403
line wrap: on
line diff
--- a/src/dirtools.c	Fri Dec 16 21:55:37 2022 -0500
+++ b/src/dirtools.c	Sun Feb 11 19:43:31 2024 -0500
@@ -13,41 +13,54 @@
 #include <windows.h>
 #include "dirtools.h"
 
-int dirtools_directory_exists(char* path) {
-	DWORD attrib = GetFileAttributesA(path);
+/* these are aids and should be converted to wchar */
+
+static int dirtools_directory_exists(LPCWSTR restrict path) {
+	DWORD attrib = GetFileAttributesW(path);
 	return (attrib != INVALID_FILE_ATTRIBUTES && (attrib & FILE_ATTRIBUTE_DIRECTORY));
 }
 
-int dirtools_create_directory(char* path) {
-	char* alltoks = calloc(strlen(path)+2, sizeof(char)), *tok;
+int dirtools_create_directory(LPCWSTR restrict path) {
+	size_t len = wcslen(path);
+	WCHAR tmp[len + 1];
+	memset(tmp, '\0', (len + 1) * sizeof(WCHAR));
 
-	for (tok = strtok(path, "\\"); tok != NULL; tok = strtok(NULL, "\\")) {
-		strcat(alltoks, tok);
-		strcat(alltoks, "\\");
-		if (dirtools_directory_exists(path)) {
-			if (!CreateDirectoryA(alltoks, NULL)) {
-				if (GetLastError() == ERROR_PATH_NOT_FOUND) {
-					/* ERROR_PATH_NOT_FOUND should NOT happen here */
-					return 1;
-				}
-			}
-		}
+	for (size_t i = 0; i < len; i++) {
+		if (path[i] != L'\\')
+			continue;
+
+		wcsncpy(tmp, path, i);
+		if (dirtools_directory_exists(tmp))
+			continue;
+
+		if (!CreateDirectoryW(tmp, NULL))
+			if (GetLastError() == ERROR_PATH_NOT_FOUND)
+				return 1;
 	}
 
-	free(alltoks);
+	if (!dirtools_directory_exists(path) && !CreateDirectoryW(path, NULL))
+		if (GetLastError() == ERROR_PATH_NOT_FOUND)
+			return 1;
 
 	return 0;
 }
 
-char* dirtools_concat_paths(char* a, char* b) {
-	if (a[0] == '\0' || b[0] == '\0')
+LPWSTR dirtools_concat_paths(LPCWSTR restrict a, LPCWSTR restrict b) {
+	if (a[0] == L'\0' || b[0] == L'\0')
 		return NULL;
-	char* out = calloc((strlen(a) + strlen(b) + 2), sizeof(char));
+
+	const size_t a_len = wcslen(a);
+	const size_t b_len = wcslen(b);
+	const int add_backslash = (a[a_len] != L'\\' && b[0] != L'\\');
+
+	LPWSTR out = calloc(a_len + b_len + 1 + add_backslash, sizeof(WCHAR));
 	if (out == NULL)
 		return out;
-	strcpy(out, a);
-	if (a[strlen(a)] != '\\' && b[0] != '\\')
-		strcat(out, "\\");
-	strcat(out, b);
+
+	wcscpy(out, a);
+	if (add_backslash)
+		wcscat(out, L"\\");
+
+	wcscat(out, b);
 	return out;
 }