How can I print a non-null-terminated string using printf, assuming that I know the length of the string at runtime?
How can I print a non-null-terminated string using printf, assuming that I know the
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Use together with other args:
In C you could specify the maximum length to output with the
%.123sformat. This means the output length is at most 123 chars. The123could be replaced by*, so that the length will be taken from the argument of printf instead of hard-coded.Note that this assumes the
stringdoes not contain any interior null bytes (\0), as%.123sonly 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
fwriteinstead:See @M.S.Dousti’s answer for detailed explanation.