开发者

C stdout printf

开发者 https://www.devze.com 2022-12-26 11:17 出处:网络
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 seco

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 prepended 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]);
   }
}


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


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消