find the length of a formatted string in C

3.3k views Asked by At

I have below function in my application:

 void func(char *file, int line)
 {
    char stmt[150];
    sprintf(stmt, "Failed in file %s, at line number %d", file, line);
 }

Here I am taking char array of 150 bytes(rough guess), instead I need to find the length of the string that I gave in sprintf() and take the array of that size.

Pls suggest me if such facility in C to find the length of a formatted string. Thanks !

1

There are 1 answers

0
Lubomír Sedlář On BEST ANSWER

What about snprintf? The function does not write more characters than given number, but returns the length of the string it would create if it had enough space.

 int len = snprintf(NULL, 0, "Failed in file %s, at line number %d", file, line);