Fork me on GitHub

Project Notes

printf partial strings

Learning how printf can be instructed to select a limited number of characters from a string.


I learned of this from the Embedded Artistry blog. It could be useful when dealing with string buffers that are not null terminated.

Basically: the width parameter of the format string applies also the string.

e.g. %.5s limits output to a maximum of 5 characters:

const char * mystr = "... long string ...";
printf("Just 5 characters: %.5s\n", mystr);

Or the * width specifier can be used to take the length as an argument:

printf("Just 5 characters: %.*s\n", 5, mystr);

This also works with related functions such as sprintf.


demo.c exercises various string format combinations. Use make to compile and run:

$ make
gcc -Wall -O0    demo.c   -o demo

===== test_explicit_printf_format
> printf("Prints just 5 characters (should print 'ABCDE'): %.5s\n", long_string);
Prints just 5 characters (should print 'ABCDE'): ABCDE

===== test_printf_width_as_argument
> printf("Prints just %d characters (should print 'AB'): %.*s\n", 2, 2, long_string);
Prints just 2 characters (should print 'AB'): AB

===== test_explicit_printf_format
> printf("Asking for 5 characters, but only 4 available (should print 'ABCD'): %.5s\n", short_string);
Asking for 5 characters, but only 4 available (should print 'ABCD'): ABCD

===== test_explicit_sprintf_format
> sprintf(result, "%.5s", long_string);

===== test_sprintf_with_width_as_argument
> sprintf(result, "%.*s", 2, long_string);

Credits and References

About LCK#167 c
Project Source on GitHub Return to the Project Catalog

This page is a web-friendly rendering of my project notes shared in the LittleCodingKata GitHub repository.

LittleCodingKata is my collection of programming exercises, research and code toys broadly spanning things that relate to programming and software development (languages, frameworks and tools).

These range from the trivial to the complex and serious. Many are inspired by existing work and I'll note credits and references where applicable. The focus is quite scattered, as I variously work on things new and important in the moment, or go back to revisit things from the past.

This is primarily a personal collection for my own edification and learning, but anyone who stumbles by is welcome to borrow, steal or reference the work here. And if you spot errors or issues I'd really appreciate some feedback - create an issue, send me an email or even send a pull-request.