]> wimlib.net Git - wimlib/blob - programs/imagex-win32.c
finish_write(): Fix comment
[wimlib] / programs / imagex-win32.c
1 /* Windows-specific code for wimlib-imagex.  */
2
3 #ifndef __WIN32__
4 #  error "This file contains Windows code"
5 #endif
6
7 #include "imagex-win32.h"
8 #include <fcntl.h>
9 #include <io.h>
10 #include <stdio.h>
11 #include <windows.h>
12
13 /* Convert a string from the "current Windows codepage" to UTF-16LE.  */
14 wchar_t *
15 win32_mbs_to_wcs(const char *mbs, size_t mbs_nbytes, size_t *num_wchars_ret)
16 {
17         if (mbs_nbytes > INT_MAX) {
18                 fwprintf(stderr, L"ERROR: too much data (%zu bytes)!\n",
19                          mbs_nbytes);
20                 return NULL;
21         }
22         if (mbs_nbytes == 0) {
23                 *num_wchars_ret = 0;
24                 return (wchar_t*)mbs;
25         }
26         int len = MultiByteToWideChar(CP_ACP,
27                                       MB_ERR_INVALID_CHARS,
28                                       mbs,
29                                       mbs_nbytes,
30                                       NULL,
31                                       0);
32         if (len <= 0)
33                 goto out_invalid;
34         wchar_t *wcs = malloc(len * sizeof(wchar_t));
35         if (!wcs) {
36                 fwprintf(stderr, L"ERROR: out of memory!\n");
37                 return NULL;
38         }
39         int len2 = MultiByteToWideChar(CP_ACP,
40                                        MB_ERR_INVALID_CHARS,
41                                        mbs,
42                                        mbs_nbytes,
43                                        wcs,
44                                        len);
45         if (len2 != len) {
46                 free(wcs);
47                 goto out_invalid;
48         }
49         *num_wchars_ret = len;
50         return wcs;
51 out_invalid:
52         fwprintf(stderr,
53 L"ERROR: Invalid multi-byte string in the text file you provided as input!\n"
54 L"       Maybe try converting your text file to UTF-16LE?\n"
55         );
56         return NULL;
57 }
58
59 static inline bool
60 is_path_separator(wchar_t c)
61 {
62         return c == L'/' || c == L'\\';
63 }
64
65 /* basename() (modifying, trailing-slash stripping version) for wide-character
66  * strings.  Understands both forward and backward slashes.  */
67 wchar_t *
68 win32_wbasename(wchar_t *path)
69 {
70         wchar_t *p = wcschr(path, L'\0');
71
72         p--;
73         while (p >= path && is_path_separator(*p))
74                 *p-- = '\0';
75         while (p >= path && !is_path_separator(*p))
76                 p--;
77         p++;
78         return p;
79 }
80
81 /* Set a file descriptor to binary mode.  */
82 void set_fd_to_binary_mode(int fd)
83 {
84         _setmode(fd, _O_BINARY);
85 }