C 标准输出 printf
我在打印数据时遇到一个奇怪的问题。我使用 printf 打印 char* 字符串,然后打印另一个字符串。但是,第一个字符串的一部分不会被打印,当我打印第二个字符串时,第一个字符串的缺失部分会被添加到该字符串的前面。这里发生了什么?
我正在写一个简单的 libpcap implementation。这是一个示例回调函数,它将产生相同的结果。我尝试在打印后删除缓冲并添加 putchar('\n') 但没有帮助。
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]);
}
}
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]);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
stdio
缓冲字符。除非您另有说明,否则通常它只会在看到换行符时才会实际发出写入操作。如果您想要不同的行为,可以使用以下一些方法来补救:在第一个
printf
之后,调用fflush(stdout);
刷新缓冲区。< /p>或者,调用
setbuf(stdout, NULL);
禁用缓冲。在执行任何printf
之前执行此操作。通过编写特定于平台的 API(例如
write
(POSIX) 或WriteFile
(Windows))来绕过stdio
。通常我会建议不要这样做,特别是对于像stdout
..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
, callfflush(stdout);
to flush the buffer.Alternatively, call
setbuf(stdout, NULL);
to disable buffering. Do this before you do anyprintf
s.Bypass
stdio
by coding to platform specific APIs likewrite
(POSIX) orWriteFile
(Windows). Usually I would recommend against this, especially for something likestdout
..您的第一个 printf 末尾可能没有 '\n' 。在某些情况下,当遇到“\n”时,数据可能会被缓冲并一起打印。
但是,这只是一个猜测。如果您无法发布代码,请尝试上述操作。
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.
这称为文件流缓冲。
您可以禁用它或使用 setvbuf() 更改缓冲区的大小。或者只是在每次打印后 fflush() 。但是,当存在行终止符 (\n) 时,流缓冲区(通常)会被刷新。
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.
我有类似的经历,但这与双字节有更多关系。我有 2 个 char* 定义背对背。我将一些字符读入第一个字符串。事实证明这是双字节,因此字符串的其余部分溢出到第二个字符串。
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.