Custom sprintf () implementation

Can someone point me to a source code file or package that has a nice, reusable sprintf () implementation in C that I can customize according to my own needs?

Explanation why I need it: strings do not have a zero end in my code (compatible with binary). Therefore, sprintf ("% s") is useless unless I correct the code to figure out how to render the string.

Thanks to quinmars for indicating that there is a way to print a line through% s without ending it with a null value. Although it solves the problem now, I will eventually need an implementation of sprintf (or snprintf) for higher level functions that use options. Of the others mentioned so far, it seems to me that the implementation of SQLite is the best. Thanks to Doug Currie for pointing this out.

+3
source share
9 answers

I have not tried because I do not have a compiler, but by reading the man page, it looks like you can pass the precision to '% s':

... ,               ;               ,              NUL.

- ?

snprintf(buffer, sizeof(buffer), "%.*s", bstring_len, bstring);

, , , , , '\ 0'- .

EDIT: , !

+5

snprintf (sprintf ); google http://www.ijs.si/software/snprintf/.

+3

SQLite .

Dickon Reed, snprintf, SQLite.

+3

. , ( glib libc).

+2
+1

, , sprintf, - , - - .

- , XML - , Lexers Parser (2 Flex Bison), ( ).

, Visual Studio ( , 2005 2008 , , 2, , ).

+1

snprintf glibc hook/handler

+1

... :

#include <stdio.h>
#include <string.h>
#include <stdarg.h>

int sprintf(char * str, const char * format, ... )    
{// Here you can redfine your input before continuing to compy with standard inputs
    va_list args;
    va_start(args, format);
    vsprintf(str,format, args);// This still uses standaes formating
    va_end(args);
    return 0;// Before return you can redefine it back if you want...
}
int main (void)
{
    char h[20];
    sprintf(h,"hei %d ",10);
    printf("t %s\n",h);
    getchar();
    return 0;
}
+1

Take a look at Hanson C Interfaces: Implementations and Methods . This is an interesting book in which it is written using Knuth Literate Programming technologies , and it includes an extensible, formatted, based input-output interface snprintf().

0
source

Source: https://habr.com/ru/post/1704198/


All Articles