Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the length of output that sprintf will generate?

Tags:

Goal: serialize data to JSON.

Issue: i cant know beforehand how many chars long the integer is.

i thought a good way to do this is by using sprintf()

size_t length = sprintf(no_buff, "{data:%d}",12312); char *buff = malloc(length); snprintf(buff, length, "{data:%d}",12312); //buff is passed on ... 

Of course i can use a stack variable like char a[256] instead of no_buff.

Question: But is there in C a utility for disposable writes like the unix /dev/null? Smth like this:

#define FORGET_ABOUT_THIS ... size_t length = sprintf(FORGET_ABOUT_THIS, "{data:%d}",12312); 

p.s. i know that i can also get the length of the integer through log but this ways seems nicer.

like image 269
alknows Avatar asked Mar 16 '15 21:03

alknows


People also ask

What does sprintf return?

The sprintf function returns the number of characters stored in the array s , not including the terminating null character. The behavior of this function is undefined if copying takes place between objects that overlap—for example, if s is also given as an argument to be printed under control of the ' %s ' conversion.

What is sprintf () in C?

sprintf() in C sprintf stands for "string print". In C programming language, it is a file handling function that is used to send formatted output to the string. Instead of printing on console, sprintf() function stores the output on char buffer that is specified in sprintf.

What is the difference between sprintf and Snprintf?

The snprintf function The main difference between snprintf and sprintf is that the former takes an argument that specifies the number of characters to write to the character array, whereas the latter does not take such an argument.

What does sprintf stand for?

sprintf stands for “String print”. Instead of printing on console, it store output on char buffer which are specified in sprintf.


1 Answers

Since C is where simple language, there is no such thing as "disposable buffers" -- all memory management are on programmers shoulders (there is GNU C compiler extensions for these but they are not standard).

cant know beforehand how many chars long the integer is.

There is much easier solution for your problem. snprintf knows!

On C99-compatible platforms call snprintf with NULL as first argument:

ssize_t bufsz = snprintf(NULL, 0, "{data:%d}",12312); char* buf = malloc(bufsz + 1); snprintf(buf, bufsz + 1, "{data:%d}",12312);  ...  free(buf); 

In older Visual Studio versions (which have non-C99 compatible CRT), use _scprintf instead of snprintf(NULL, ...) call.

like image 184
myaut Avatar answered Oct 02 '22 08:10

myaut