diff options
author | Yuqian Yang <crupest@crupest.life> | 2025-04-01 23:44:50 +0800 |
---|---|---|
committer | Yuqian Yang <crupest@crupest.life> | 2025-04-02 19:00:58 +0800 |
commit | 4182874b764ea3d6ec6224e1b4d0f1b38ff78c05 (patch) | |
tree | 089b061146913b7b8afa36c56cc5c64cb1124cc7 /www/content/posts/c-func-ext.md | |
parent | 6e266e43ddbd99cadc814190c54eb77890f42479 (diff) | |
download | crupest-4182874b764ea3d6ec6224e1b4d0f1b38ff78c05.tar.gz crupest-4182874b764ea3d6ec6224e1b4d0f1b38ff78c05.tar.bz2 crupest-4182874b764ea3d6ec6224e1b4d0f1b38ff78c05.zip |
feat(www): update.
Diffstat (limited to 'www/content/posts/c-func-ext.md')
-rw-r--r-- | www/content/posts/c-func-ext.md | 64 |
1 files changed, 39 insertions, 25 deletions
diff --git a/www/content/posts/c-func-ext.md b/www/content/posts/c-func-ext.md index f0fce10..7106fad 100644 --- a/www/content/posts/c-func-ext.md +++ b/www/content/posts/c-func-ext.md @@ -19,9 +19,11 @@ reusable code snippets here to help *fix `*_MAX` bugs*. <!--more--> ```c -#include <errno.h> #include <stdlib.h> +#include <stdarg.h> #include <unistd.h> +#include <stdio.h> +#include <errno.h> static inline char *xreadlink(const char *restrict path) { char *buffer; @@ -29,24 +31,18 @@ static inline char *xreadlink(const char *restrict path) { ssize_t len; while (1) { - buffer = (char *)malloc(allocated); - if (!buffer) { - return NULL; - } + buffer = (char*) malloc(allocated); + if (!buffer) { return NULL; } len = readlink(path, buffer, allocated); - if (len < (ssize_t)allocated) { - return buffer; - } + if (len < (ssize_t) allocated) { return buffer; } free(buffer); - if (len >= (ssize_t)allocated) { - allocated *= 2; - continue; - } + if (len >= (ssize_t) allocated) { allocated *= 2; continue; } return NULL; } -} + } + -static inline char *xgethostname() { +static inline char *xgethostname(void) { long max_host_name; char *buffer; @@ -62,24 +58,42 @@ static inline char *xgethostname() { return buffer; } -static inline char *xgetcwd() { +static inline char *xgetcwd(void) { char *buffer; size_t allocated = 128; while (1) { - buffer = (char *)malloc(allocated); - if (!buffer) { - return NULL; - } + buffer = (char*) malloc(allocated); + if (!buffer) { return NULL; } getcwd(buffer, allocated); - if (buffer) - return buffer; + if (buffer) return buffer; free(buffer); - if (errno == ERANGE) { - allocated *= 2; - continue; - } + if (errno == ERANGE) { allocated *= 2; continue; } return NULL; } } + +static inline __attribute__((__format__(__printf__, 2, 3))) int +xsprintf(char **buf_ptr, const char *restrict format, ...) { + char *buffer; + int ret; + + va_list args; + va_start(args, format); + + ret = snprintf(NULL, 0, format, args); + if (ret < 0) { goto out; } + + buffer = malloc(ret + 1); + if (!buffer) { ret = -1; goto out; } + + ret = snprintf(NULL, 0, format, args); + if (ret < 0) { free(buffer); goto out; } + + *buf_ptr = buffer; + +out: + va_end(args); + return ret; +} ``` |