Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printf a buffer of char with length in C

Tags:

I have a buffer which I receive through a serial port. When I receive a certain character, I know a full line has arrived, and I want to print it with printf method. But each line has a different length value, and when I just go with:

printf("%s", buffer); 

I'm printing the line plus additional chars belonging to the former line (if it was longer than the current one).

I read here that it is possible, at least in C++, to tell how much chars you want to read given a %s, but it has no examples and I don't know how to do it in C. Any help?

I think I have three solutions:

  • printing char by char with a for loop
  • using the termination character
  • or using .*

QUESTION IS: Which one is faster? Because I'm working on a microchip PIC and I want it to happen as fast as possible

like image 526
Roman Rdgz Avatar asked Nov 17 '11 16:11

Roman Rdgz


People also ask

How do you print only part of a string in C?

You can use strncpy to duplicate the part of your string you want to print, but you'd have to take care to add a null terminator, as strncpy won't do that if it doesn't encounter one in the source string.


2 Answers

You can either add a null character after your termination character, and your printf will work, or you can add a '.*' in your printf statement and provide the length

printf("%.*s",len,buf); 

In C++ you would probably use the std::string and the std::cout instead, like this:

std::cout << std::string(buf,len); 

If all you want is the fastest speed and no formatting -- then use

fwrite(buf,1,len,stdout); 
like image 72
Soren Avatar answered Oct 30 '22 15:10

Soren


The string you have is not null-terminated, so, printf (and any other C string function) cannot determine its length, thus it will continue to write the characters it finds there until it stumbles upon a null character that happens to be there.

To solve your problem you can either:

  • use fwrite over stdout:

    fwrite(buffer, buffer_length, 1, stdout); 

    This works because fwrite is not thought for printing just strings, but any kind of data, so it doesn't look for a terminating null character, but accepts the length of the data to be written as a parameter;

  • null-terminate your buffer manually before printing:

    buffer[buffer_length]=0; printf("%s", buffer); /* or, slightly more efficient: fputs(buffer, stdout); */ 

    This could be a better idea if you have to do any other string processing over buffer, that will now be null-terminated and so manageable by normal C string processing functions.

like image 27
Matteo Italia Avatar answered Oct 30 '22 17:10

Matteo Italia