Browse Source

Implement PATH_EXISTS

rexim 4 năm trước cách đây
mục cha
commit
c2d67ab0f8
2 tập tin đã thay đổi với 27 bổ sung0 xóa
  1. 4 0
      examples/file.c
  2. 23 0
      nobuild.h

+ 4 - 0
examples/file.c

@@ -24,6 +24,10 @@ int main(void)
     DEMO(IS_DIR("./examples"));
     DEMO(IS_DIR("./file_that_does_not_exist"));
 
+    DEMO(PATH_EXISTS("./nobuild.c"));
+    DEMO(PATH_EXISTS("./examples"));
+    DEMO(PATH_EXISTS("./file_that_does_not_exist"));
+
     INFO("Recursively traversing the file system");
     print_file_recursively(".");
 

+ 23 - 0
nobuild.h

@@ -203,6 +203,9 @@ void chain_echo(Chain chain);
 int path_is_dir(Cstr path);
 #define IS_DIR(path) path_is_dir(path)
 
+int path_exists(Cstr path);
+#define PATH_EXISTS(path) path_exists(path)
+
 void path_mkdirs(Cstr_Array path);
 #define MKDIRS(...)                                             \
     do {                                                        \
@@ -864,6 +867,26 @@ void chain_echo(Chain chain)
     printf("\n");
 }
 
+int path_exists(Cstr path)
+{
+#ifdef _WIN32
+    DWORD dwAttrib = GetFileAttributes(path);
+    return (dwAttrib != INVALID_FILE_ATTRIBUTES);
+#else
+    struct stat statbuf = {0};
+    if (stat(path, &statbuf) < 0) {
+        if (errno == ENOENT) {
+            return 0;
+        }
+
+        PANIC("could not retrieve information about file %s: %s",
+              path, strerror(errno));
+    }
+
+    return 1;
+#endif
+}
+
 int path_is_dir(Cstr path)
 {
 #ifdef _WIN32