Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the number of characters output in a fprintf '%s' format using a variable?

Tags:

c

file

printf

I need to write a variable number of characters to a file. For example, lets say I want to print 3 characters. "TO" would print "TO" to a file. "LongString of Characters" would print "Lon" to a file.

How can I do this? (the number of characters is defined in another variable). I know that this is possible fprintf(file,"%10s",string), but that 10 is predefined

like image 616
Señor Reginold Francis Avatar asked Nov 29 '22 19:11

Señor Reginold Francis


1 Answers

This one corresponds to your example:

fprintf(file, "%*s", 10, string);

but you mentioned a maximum as well, to also limit the number:

fprintf(file, "%*.*s", 10, 10, string);
like image 101
DigitalRoss Avatar answered Dec 06 '22 20:12

DigitalRoss