How to printf 'n' characters from a char* to a file?

J

Jonathan

Hi,

Can you please tell me how can I printf 'n' characters of from a char*
to a file.

I notice there is a snprinf, but I don't see one corresponding to
fprintf?

I am thinking if i can do that without an extra memcpy.

Thank you for any help.
 
W

Walter Roberson

Jonathan said:
Can you please tell me how can I printf 'n' characters of from a char*
to a file.
I notice there is a snprinf, but I don't see one corresponding to
fprintf?
I am thinking if i can do that without an extra memcpy.

printf("%.*s", n, TheCharPointer);

Or if n is known ahead of time and fixed, it can be hard-coded,
such as

printf("%.5s", TheCharPointer);

If the string does not contain at least n characters, you have
a problem. Also, the behaviour is not explicitly defined
(at least not in C89) if the string pointed to does not contain a 0
before the end of the object: you are still technically responsible
for passing a string in the parameter position, even if you've told
it to only copy so many characters out of the string.
 
H

Harald van Dijk

printf("%.*s", n, TheCharPointer);
[...]
Also, the behaviour is not explicitly defined (at least not in
C89) if the string pointed to does not contain a 0 before the end of the
object:

<nit>If the array pointed to does not contain a 0 before the end of the
object said:
you are still technically responsible for passing a string in
the parameter position, even if you've told it to only copy so many
characters out of the string.

Really? Could you show what C89 says? I don't have a copy of it, but I'm
interested because both a draft and text based on the official standard do
make it clear '\0' is not required, and the text in both is largely
identical:

C89 draft:
"Characters from the array are written up to (but not including) any
terminating null character; if the precision is specified, no more than
that many characters are written. If the precision is not specified or is
greater than the size of the array, the array shall contain a null
character."

SUSv2, based on C89:
"Bytes from the array are written up to (but not including) any
terminating null byte. If the precision is specified, no more than that
many bytes are written. If the precision is not specified or is greater
than the size of the array, the array must contain a null byte."

I would be very surprised if this text was present in the drafts, dropped
from the C89 standard, only to be added again afterwards by both SUS and
C99.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,434
Messages
2,571,691
Members
48,796
Latest member
Greg L.

Latest Threads

Top