Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stand-alone portable snprintf(), independent of the standard library?

I am writing code for a target platform with NO C-runtime. No stdlib, no stdio. I need a string formatting function like snprintf but that should be able to run without any dependencies, not even the C library.

At most it can depend on memory alloc functions provided by me.

I checked out Trio but it needs stdio.h header. I can't use this.

Edit

Target platform : PowerPC64 home made OS(not by me). However the library shouldn't rely on OS specific stuff.

Edit2

I have tried out some 3rd-party open source libs, such as Trio(http://daniel.haxx.se/projects/trio/), snprintf and miniformat(https://bitbucket.org/jj1/miniformat/src) but all of them rely on headers like string.h, stdio.h, or(even worse) stdlib.h. I don't want to write my own implementation if one already exists, as that would be time-wasting and bug-prone.

like image 357
MemCtrl Avatar asked Oct 16 '13 20:10

MemCtrl


2 Answers

Try using the snprintf implementation from uclibc. This is likely to have the fewest dependencies. A bit of digging shows that snprintf is implemented in terms of vsnprintf which is implemented in terms of vfprintf (oddly enough), it uses a fake "stream" to write to string.

This is a pointer to the code: http://git.uclibc.org/uClibc/tree/libc/stdio/_vfprintf.c

Also, a quick google search also turned up this:

  • http://www.ijs.si/software/snprintf/
  • http://yallara.cs.rmit.edu.au/~aholkner/psnprintf/psnprintf.html
  • http://www.jhweiss.de/software/snprintf.html

Hopefully one is suitable for your purposes. This is likely to not be a complete list.

There is a different list here: http://trac.eggheads.org/browser/trunk/src/compat/README.snprintf?rev=197

like image 145
Alex I Avatar answered Nov 10 '22 20:11

Alex I


You will probably at least need stdarg.h or low level knowledge of the specific compiler/architecture calling convention in order to be able to process the variadic arguments.

I have been using code based on Kustaa Nyholm's implementation It provides printf() (with user supplied character output stub) and sprintf(), but adding snprintf() would be simple enough. I added vprintf() and vsprintf() for example in my implementation.

No dynamic memory application is required, but it does have a dependency on stdarg.h, but as I said, you are unlikely to be able to get away without that for any variadic function - though you could potentially implement your own.

like image 40
Clifford Avatar answered Nov 10 '22 20:11

Clifford