Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

c - How do I print a non-null-terminated string using printf?

How can I print a non-null-terminated string using printf, assuming that I know the length of the string at runtime?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
printf("%.*s", length, string);

Use together with other args:

printf("integer=%d, string=%.*s, number=%f", integer, length, string, number);
//                         ^^^^                       ^^^^^^^^^^^^^^

In C you could specify the maximum length to output with the %.123s format. This means the output length is at most 123 chars. The 123 could be replaced by *, so that the length will be taken from the argument of printf instead of hard-coded.

Note that this assumes the string does not contain any interior null bytes (), as %.123s only constrains the maximum length not the exact length, and strings are still treated as null-terminated.

If you want to print a non-null-terminated string with interior null, you cannot use a single printf. Use fwrite instead:

fwrite(string, 1, length, stdout);

See @M.S.Dousti's answer for detailed explanation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...