tags:

views:

69

answers:

4
function(char* name)
{       
   char sql[50];
   sprintf(sql, "select %s;", name);
}

What's the best way to make sure only 50 chars of name are copied to sql in the case name is larger than what sql can hold? (sprintf with a N parameter?)

Thank You.

+1  A: 

snprintf, although it does not null terminate if you print N characters.

MSN
Actually, `snprintf` always does null-terminate the output. `strncpy` is the function you need to watch out for.
Joey Adams
Some older compilers (pre C99) did have the problem that did not null terminate if the buffer limit is reached.
richb
+6  A: 

There is snprintf, which also takes a size parameter:

int snprintf(char *str, size_t size, const char *format, ...);
sth
+1  A: 

Most compilers have an snprintf() function.

richb
+1  A: 

You want snprintf().

int snprintf(char *str, size_t size, const char *format, ...);
John R. Strohm