Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you print a limited number of characters?

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?

like image 262
Mike Pateras Avatar asked Apr 15 '10 00:04

Mike Pateras


2 Answers

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).

like image 174
R Samuel Klatchko Avatar answered Nov 05 '22 10:11

R Samuel Klatchko


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

printf("%.5s", data); // formatting string is the first parameter
like image 4
Khaled Alshaya Avatar answered Nov 05 '22 10:11

Khaled Alshaya