假设我有一段代码可以打印出像这样的内容
u_int packetCount = 0;
while (int returnValue = pcap_next_ex(pcap, &header, &data) >= 0)
{
// Show the packet number
printf("Packet # %i\n", ++packetCount);
// Show the size in bytes of the packet
printf("Packet size: %d bytes\n", header->len);
// Show a warning if the length captured is different
if (header->len != header->caplen)
printf("Warning! Capture size different than packet size: %ld bytes\n", header->len);
// Show Epoch Time
printf("Epoch Time: %d:%d seconds\n", header->ts.tv_sec, header->ts.tv_usec);
// loop through the packet and print it as hexidecimal representations of octets
// We also have a function that does this similarly below: PrintData()
for (u_int i=0; (i < header->caplen ) ; i++)
{
// Start printing on the next after every 16 octets
if ( (i % 16) == 0) printf("\n");
// Print each octet as hex (x), make sure there is always two characters (.2).
printf("%.2x ", data[i]);
}
// Add two lines between packets
printf("\n\n");
}
最后一行给出了像
这样的输出Packet # 39
Packet size: 54 bytes
Epoch Time: 1084443432:328438 seconds
fe ff 20 00 01 00 00 00 01 00 00 00 08 00 45 00
00 28 0f 5c 40 00 80 06 91 d8 91 fe a0 ed 41 d0
e4 df 0d 2c 00 50 38 af ff f3 11 4c a9 48 50 10
24 14 31 71 00 00
Packet # 40
Packet size: 54 bytes
Epoch Time: 1084443445:216971 seconds
00 00 01 00 00 00 fe ff 20 00 01 00 08 00 45 00
00 28 c0 ad 40 00 2f 06 31 87 41 d0 e4 df 91 fe
a0 ed 00 50 0d 2c 11 4c a9 48 38 af ff f3 50 11
19 20 3c 64 00 00
Packet # 41
Packet size: 54 bytes
Epoch Time: 1084443445:216971 seconds
fe ff 20 00 01 00 00 00 01 00 00 00 08 00 45 00
00 28 0f 5f 40 00 80 06 91 d5 91 fe a0 ed 41 d0
e4 df 0d 2c 00 50 38 af ff f3 11 4c a9 49 50 10
24 14 31 70 00 00
Packet # 42
Packet size: 54 bytes
Epoch Time: 1084443457:374452 seconds
fe ff 20 00 01 00 00 00 01 00 00 00 08 00 45 00
00 28 0f 62 40 00 80 06 91 d2 91 fe a0 ed 41 d0
e4 df 0d 2c 00 50 38 af ff f3 11 4c a9 49 50 11
24 14 31 6f 00 00
我需要打印此行的输出“printf("%.2x ", data[i]);
“然后将此输出写入C ++文件中。我可以知道该怎么做吗?
答案 0 :(得分:0)
查看fstream
标准库。可以在here找到写入文件的示例。
答案 1 :(得分:0)
使用std::setw
和std::hex
来控制宽度和数字的打印方式。 std::dec
会将您带回十进制(基数为10)格式。使用std::setfill('0')
填充零。
[我应该指出,在所有已知的实施方案中,fstream
会在内部调用printf
[或更可能snprintf
或某些类似的函数],因此除了“看起来像C ++”使用fstream
而不是fprintf
]