2012-09-28 44 views
0

我試圖從HTTP流中提取圖像。我有一個使用C++和其他庫的要求,除了libpcap捕獲數據包。下面是我在做什麼:寫入圖像

if ((tcp->th_flags & TH_ACK) != 0) { 
       i = tcp->th_ack; 
       const char *payload = (const char *) (packet + SIZE_ETHERNET + size_ip + size_tcp); 
       size_payload = ntohs(ip->ip_len) - (size_ip + size_tcp); 
       std::string temp(payload); 
       dict.insert(std::pair<u_int,std::string>(tcp->th_ack,temp)); 
     } 

然後,我串連它們具有相同的ACK編號的所有數據包:

std::string ss; 
for(itt=dict.begin(); itt!= dict.end(); ++itt) { 
       std::string temp((*itt).second); 
       ss.append(temp); 
    } 
    std::ofstream file; 
    file.open("image.jpg", std::ios::out | std::ios::binary) 
    file << ss; 
    file.close(); 

現在,當我寫ss到一個文件,該文件的大小是這樣小於傳輸的圖像。這是編寫二進制文件的正確方法嗎?

我試圖做this在C++

回答

1

使用的std :: string將在第一個空終止字符(即使的std :: string不是空值終止字符串)減少你的數據。 std :: string的構造函數接受一個char *並假定一個以null結尾的字符串。這是一個證明:

char sample [] = {'a', 'b', '\0', 'c', 'd', '\0', 'e'}; 
std::string ss(sample); 

您應該使用std :: vector來存儲您的數據。

+0

This Works,thanks! –

+0

我意識到我需要在將數據寫入文件之前更改字節順序。我如何做一塊數據?對'長'和'短'我可以使用'ntohs'和'ntohl'。我如何做一個字節的矢量? –