Created
February 21, 2022 21:02
-
-
Save steinerkelvin/922fdd21fbdb9b656da3f2778dbce7d3 to your computer and use it in GitHub Desktop.
auto_sprintf
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
#define ASPTF_ARGS _BUFFER, _TAM | |
/** | |
* Aloca automaticamente o espaço necessário para uma string formatada | |
* resultante de um "sprintf". | |
* | |
* @param dest Variável onde armazenar a string formatada resultante | |
* @param sptf Expressão de snprintf que deve ser do formato: | |
* `snprintf(ASPTF_ARGS, <formato>, ... )`, que é equivalente a: | |
* `snprintf(_BUFFER, _TAM, <formato>, ... )` | |
* sendo _BUFFER, _TAM varáveis internas da macro | |
*/ | |
#define auto_sprintf(dest, sptf) \ | |
{ \ | |
size_t _TAM = 32; /* tamanho inicial */ \ | |
char *_BUFFER = (char*) malloc(_TAM); \ | |
/* Executa `sptf`, que retorna o número de caracteres que seriam */ \ | |
/* escritos em `_BUFFER` caso este tivesse o tamanho adequado */ \ | |
int tam = (sptf) + 1; \ | |
if (tam > _TAM) { /* se não tem o tamanho adequado */ \ | |
/* realoca com o novo tamanho */ \ | |
char *new = (char*) realloc(_BUFFER, tam); \ | |
if (new) { \ | |
_BUFFER = new; \ | |
_TAM = tam; \ | |
/* Executa `sptf` novamente */ \ | |
(sptf); \ | |
} \ | |
} \ | |
/* Escreve o resultado na variável de destino */ \ | |
(dest) = _BUFFER; \ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment