Skip to content

Instantly share code, notes, and snippets.

@croepha
Created January 22, 2017 21:12
Show Gist options
  • Save croepha/030d0531417b20de28afbeb1711bb9fe to your computer and use it in GitHub Desktop.
Save croepha/030d0531417b20de28afbeb1711bb9fe to your computer and use it in GitHub Desktop.
Example of doing normal printf with Jeff Robert's sprintf
#if 0 /* (sh-mode)
set -e
LPATH=/Users/cro/Documents/PersonalProjects/Misc
tu_name=stb_printf_test
# -Ofast
[ ! ]&& time clang++ -g --std=c++11 -fPIC -Wall \
$LPATH/${tu_name}.cpp \
-Wno-writable-strings \
-Wno-unused-function \
-Wno-deprecated-declarations \
-I /Users/cro/Documents/shared \
-o $LPATH/${tu_name}.bin
[ ! ]&&{
# ulimit -c unlimited
$LPATH/${tu_name}.bin
}
true
exit # (c++-mode)
*/
#endif
#include <unistd.h>
#include <assert.h>
#define STB_SPRINTF_IMPLEMENTATION
// #define STB_SPRINTF_MIN 16 // Just for testing
#include <stb/stb_sprintf.h>
#define stdout 1
char * __print_cb(char * buf, void * user_, int len ) {
auto user = (char*)user_;
auto r = write(stdout, buf, len);
assert(r == len);
return user;
}
void print(char const *fmt, ...) {
va_list va;
va_start( va, fmt );
char buf[STB_SPRINTF_MIN];
auto len = stbsp_vsprintfcb( __print_cb, buf, buf, fmt, va );
assert (len >0);
va_end(va);
// auto r = write(stdout, buf, len - 1);
// assert(r == len - 1);
fsync(stdout);
}
int main() {
print("zero\n");
print("abcdefghijf1abcdefghijf2abcdefghijf3abcdefghijf4abcdefghijf5abcdefghijf6abcdefghijf7\n");
print("Float: %0*.*f\n", 8, 3, 2.4);
print("one\n");
// char buf2[] = "ABCD\0ABCD\0ABCD";
// auto r = write(stdout, buf2, sizeof(buf2));
print("two\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment