From 9b2a662f26e3eb8e58b465290d961cda410e56a5 Mon Sep 17 00:00:00 2001 From: Aoran Zeng Date: Sun, 10 Sep 2023 13:15:34 +0800 Subject: [PATCH] Add `xy_file_exist()` --- Makefile | 1 + test_xy.c | 4 +++- xy.h | 22 +++++++++++++++++++++- 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 6f7f512..3bf88e8 100644 --- a/Makefile +++ b/Makefile @@ -31,6 +31,7 @@ test: $(TARGET) ./$(TARGET) get ruby ./$(TARGET) get python +.PHONY: xy xy: @$(CC) test_xy.c -o xy @./xy diff --git a/test_xy.c b/test_xy.c index 5d4e7e2..bd73039 100644 --- a/test_xy.c +++ b/test_xy.c @@ -3,7 +3,7 @@ * License : MIT * Authors : Aoran Zeng * Created on : <2023-08-30> - * Last modified : <2023-09-09> + * Last modified : <2023-09-10> * * test_xy: * @@ -70,5 +70,7 @@ main (int argc, char const *argv[]) xy_info("信息: 输出信息内容"); xy_warn("警告:输出警告内容"); xy_error("错误:输出错误内容"); + + putb(xy_file_exist("chsrc.png")); return 0; } diff --git a/xy.h b/xy.h index 41edf1a..60614a3 100644 --- a/xy.h +++ b/xy.h @@ -30,6 +30,8 @@ #ifdef _WIN32 + #include // For access() + static bool xy_on_windows = true; static bool xy_on_linux = false; static bool xy_on_macos = false; @@ -445,7 +447,8 @@ xy_str_strip (const char* str) return new; } -/* * + +/** * 执行cmd后拿到cmd的执行结果 注意从外部free掉这段内存 * 注意:执行结果后面有回车换行 */ @@ -491,5 +494,22 @@ xy_getcmd(const char * cmd, bool (*func)(const char*)) } +/** + * @note Windows上,`path` 不要夹带变量名,因为最终 access() 不会帮你转换 + */ +bool +xy_file_exist(char* path) +{ + char* newpath = path; + if (xy_on_windows) + { + char* home = getenv("USERPROFILE"); + if (xy_str_start_with(path, "~")) { + newpath = xy_2strjoin(home, path+1); + } + } + return access(newpath, 0) ? false : true; +} + #endif