How do you print a limited number of characters?

Sorry to post 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 is to read data from a file and then print only 5 characters. However, it prints all 1024 characters, which contradicts what I read here . The goal, of course, is to do something like:

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

What am I doing wrong here?

+7
c string formatting printf
source share
4 answers

You have your options in the wrong order. It should be written:

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

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

+24
source share

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

 printf("%.5s", data); // formatting string is the first parameter 
+4
source share

You are not calling printf () correctly.

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

What does it mean ...

 printf("%.5s", data); 
+1
source share

You are using the wrong syntax for the printf operator, and the number. only for numeric variables.

So what it should be

 int i; for(i=0;i<5;i++) printf("%c", data[i]); 
-2
source share

All Articles