tags:

views:

93

answers:

4

I have a weird issue with printing data out. I use printf to print a char* string and then after that print another one. However part of the first string doesn't get printed and when I print the second string the missing part of the first one is pretended to that one. What is happening here?

I'm writting a simple libpcap implimentation. Here is a sample callback function that will produce the same results. I tried removing buffering and adding a putchar('\n') after printing but it didn't help.

void ParseData(u_char* useless ,const struct pcap_pkthdr* pkthdr,const u_char* packet){
   int packetLen,i;
   packetLen = pkthdr->len;
   for(i=0;i<packetLen;i++){
      putchar(packet[i]);
   }
}
+1  A: 

There is a possibility that your first printf is not having a '\n' at the end. In some cases the data might be buffered and printed together when a '\n' is encountered.

But, this is just a guess. Incase if you cannot post code, try the above.

Jay
+6  A: 

stdio buffers characters. Unless you tell it otherwise, usually it will only actually issue a write when it sees a newline character. If you want a different behavior, you can remedy it with some of these:

  • After your first printf, call fflush(stdout); to flush the buffer.

  • Alternatively, call setbuf(stdout, NULL); to disable buffering. Do this before you do any printfs.

  • Bypass stdio by coding to platform specific APIs like write (POSIX) or WriteFile (Windows). Usually I would recommend against this, especially for something like stdout..

asveikau
A: 

I have a similar experience but this has more to do with double byte. I have 2 char* define back to back. I read some char into the first string. Turns out that is was double byte, so the remaining of the string spill over to the second string.

Chuk Lee
A: 

It's called file stream buffering.

You can disable it or change the size of the buffer using setvbuf(). Or just fflush() after every print. However, the stream buffer is (normally) flushed when a line terminator (\n) is present.

jweyrich