Last active
February 9, 2024 10:39
-
-
Save opsJson/ce29f980360713b74e4abc152217849a to your computer and use it in GitHub Desktop.
Easily allocate strings with a printf-like function.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdarg.h> | |
#include <wchar.h> | |
char *makestr(char *format, ...) { | |
va_list args; | |
int size; | |
char *result; | |
#if !defined(_WIN32) | |
FILE *printf_dummy_file = fopen("/dev/null", "wb"); | |
#else | |
FILE *printf_dummy_file = fopen("NUL", "wb"); | |
#endif | |
va_start(args, format); | |
size = vfprintf(printf_dummy_file, format, args); | |
result = malloc(size + 1); | |
if (result == NULL) return NULL; | |
va_end(args); | |
va_start(args, format); | |
vsnprintf(result, size + 1, format, args); | |
result[size] = '\0'; | |
fclose(printf_dummy_file); | |
return result; | |
} | |
wchar_t *wmakestr(wchar_t *format, ...) { | |
va_list args; | |
int size; | |
wchar_t *result; | |
#if !defined(_WIN32) | |
FILE *printf_dummy_file = fopen("/dev/null", "wb"); | |
#else | |
FILE *printf_dummy_file = fopen("NUL", "wb"); | |
#endif | |
va_start(args, format); | |
size = vfwprintf(printf_dummy_file, format, args) * sizeof(wchar_t); | |
result = malloc(size + 2); | |
if (result == NULL) return NULL; | |
va_end(args); | |
va_start(args, format); | |
vswprintf(result, size + 2, format, args); | |
result[size] = L'\0'; | |
fclose(printf_dummy_file); | |
return result; | |
} | |
/*/////////////////////////////////// | |
Testing: | |
///////////////////////////////////*/ | |
int main(void) { | |
char *str = makestr("Hello, %s! %i -> %2.1f", "word", 69, 2.5000f); | |
wchar_t *wstr = wmakestr(L"Hello, %ls! %i -> %2.1f", L"word", 69, 2.5000f); | |
printf("%s\n", str); | |
wprintf(L"%ls\n", wstr); | |
free(str); | |
free(wstr); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment