views:

99

answers:

4

Sorry to put a post up about something so simple, but I don't see what I'm doing wrong here.

char data[1024];
DWORD numRead;

ReadFile(handle, data, 1024, &numRead, NULL);

if (numRead > 0)
    printf(data, "%.5s");

My intention with the above is to read data from a file, and then only print out 5 characters. However, it prints out all 1024 characters, which is contrary to what I'm reading here. The goal, of course, is to do something like:

printf(data, "%.*s", numRead);

What am I doing wrong here?

+2  A: 

I think you are switching the order of arguments to printf:

printf("%.5s", data); // formatting string is the first parameter
AraK
+5  A: 

You have your parameters in the wrong order. The should be written:

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

printf("%.*s", numRead, data);

The first parameter to printf is the format specifier followed by all the arguments (which depend on your specifier).

R Samuel Klatchko
A: 

You are using wrong syntax for the printf statement, and the .number is only for numerical variables.

So it should be

int i;
for(i=0;i<5;i++)
   printf("%c", data[i]);
sjchoi
.number works just fine with character arrays, he just needs to put the arguments in the right order.
Brian Roach
For strings, precision (i.e. the .numbers) tells printf to print no more then N characters from the string. This is very useful if your string is not '\0' terminated.
R Samuel Klatchko
Wow. Learned something new. I always just assumed. Thanks.
sjchoi
+1  A: 

You're not calling printf() correctly.

int printf ( const char * format, ... );

Which means...

printf("%.5s", data);
Brian Roach