Cthulhu  0.2.10
Cthulhu compiler collection
fs.c
Go to the documentation of this file.
1 // SPDX-License-Identifier: LGPL-3.0-only
2 
3 #include "base/panic.h"
4 
5 #include "core/win32.h" // IWYU pragma: keep
6 
7 #include "os/os.h"
8 
9 #include <limits.h>
10 
12 os_error_t os_file_delete(const char *path)
13 {
14  BOOL result = DeleteFileA(path);
15 
16  if (!result)
17  {
18  return GetLastError();
19  }
20 
21  return ERROR_SUCCESS;
22 }
23 
25 os_error_t os_dir_create(const char *path)
26 {
27  CTASSERT(path != NULL);
28 
29  BOOL result = CreateDirectoryA(path, NULL);
30  if (!result)
31  {
32  DWORD error = GetLastError();
33  if (error == ERROR_ALREADY_EXISTS)
34  {
35  return eOsExists;
36  }
37 
38  return error;
39  }
40 
41  return eOsSuccess;
42 }
43 
45 os_error_t os_dir_delete(const char *path)
46 {
47  BOOL result = RemoveDirectoryA(path);
48  if (!result)
49  {
50  return GetLastError();
51  }
52 
53  return ERROR_SUCCESS;
54 }
55 
57 os_dirent_t os_dirent_type(const char *path)
58 {
59  DWORD attributes = GetFileAttributesA(path);
60 
61  if (attributes != INVALID_FILE_ATTRIBUTES)
62  {
63  // TODO: this doesnt handle pipes, sockets, etc.
64  return (attributes & FILE_ATTRIBUTE_DIRECTORY)
65  ? eOsNodeDir
66  : eOsNodeFile;
67  }
68 
69  DWORD error = GetLastError();
70  if (error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND)
71  {
72  return eOsNodeNone;
73  }
74 
75  return eOsNodeError;
76 }
77 
79 size_t os_cwd_get_string(char *buffer, size_t size)
80 {
81  CTASSERTF(size < UINT_MAX, "size %zu is too large", size);
82 
83  if (size == 0)
84  CTASSERT(buffer == NULL);
85  else
86  CTASSERT(buffer != NULL);
87 
88  return GetCurrentDirectoryA((DWORD)size, buffer);
89 }
CT_NODISCARD size_t size
Definition: scan.h:128
os_dirent_t
directory entry type
Definition: core.h:56
#define STA_DECL
sal2 annotation on function implementations to copy annotations from the declaration
#define CTASSERT(expr)
assert a condition, prints the condition as a message
Definition: panic.h:130
#define CTASSERTF(expr,...)
assert a condition with a message and optional format arguments
Definition: panic.h:116
STA_DECL size_t os_cwd_get_string(char *buffer, size_t size)
Definition: fs.c:93
STA_DECL os_error_t os_dir_create(const char *path)
check if a directory exists
Definition: fs.c:29
STA_DECL os_dirent_t os_dirent_type(const char *path)
get the type of a paths inode entry
Definition: fs.c:65
STA_DECL os_error_t os_file_delete(const char *path)
delete a file
Definition: fs.c:16
STA_DECL os_error_t os_dir_delete(const char *path)
delete a directory
Definition: fs.c:52
@ eOsExists
Definition: posix.h:26
@ eOsSuccess
Definition: posix.h:24