2012-07-11 67 views
1

這是我的問題,我想打開一個.jpg文件,並用逗號分隔每個字節作爲十進制數字(0-255),轉換爲另一個.txt文件。現在它應該能夠使用該txt文件再次構建.jpf文件。這是我試圖做到這一點。從二進制文件中逐個讀取字節

#include<iostream> 
#include<fstream> 
using namespace std; 
int main() 
{ 
long x; 
char *s; 

ifstream ifs("image.jpg",ios::binary); 
ifs.seekg(0,ios::end); 
x=ifs.tellg(); 
ifs.seekg(0,ios::beg); 

s=new char[x]; 
ifs.read(s,x); 
ifs.close(); 

ofstream is("image.txt"); 

for(int i=0;i<x;i++){ 
is<<(unsigned int)s[i]<<","; 
} 

現在這個程序及牡丹image.txt與十進制數如下, 4294967295,4294967256,4294967295,4294967264,0,16,74,70,73,70,0,1,..... 。 這裏有些數字似乎是4字節長,s [i]只指一個字節,所以如何可以(int)s [i]返回一個大於255的數字。請有人可以幫助我.... this thanks ..

+8

您正在讀取的字符不是從0到255的無符號數,而是從-128到+127的有符號數。當你投射到無符號整數時,負數會變成大數正數。嘗試使用無符號字符數組。 – 2012-07-11 14:55:01

回答

13

它似乎在您的機器上char簽署。所以當你投一個負數到unsigned int時,你會得到一個很大的價值。當使用char來表示它們時,輸出中的大值是負值。請注意,當char簽署,其價值可-128127字節可以是2550之間。因此,大於127的任何值都會在範圍-128 to -1之間變爲負值。

使用unsigned char爲:

unsigned char *s; 

還是做到這一點:

is<< static_cast<unsigned int> (static_cast<unsigned char>(s[i]))<<","; 
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
           casting to unsigned char first 
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
       then casting to unsigned int 

也就是說,投第一charunsigned char,然後unsigned int


那麼這就是你面臨的問題。現在一些關於風格和成語的筆記。在C++中,應儘可能避免使用new。你的情況,你可以使用std::vector爲:

//define file stream object, and open the file 
std::ifstream file("image.jpg",ios::binary); 

//prepare iterator pairs to iterate the file content! 
std::istream_iterator<unsigned char> begin(file), end; 

//reading the file content using the iterator! 
std::vector<unsigned char> buffer(begin,end); 

最後一行從文件中的所有數據讀入buffer

std::copy(buffer.begin(), 
      buffer.end(), 
      std::ostream_iterator<unsigned int>(std::cout, ",")); 

對於所有這些工作,需要包括除下列頭到你已經在你的代碼已經被添加:

#include <vector>  //for vector 
#include <iterator> //for std::istream_iterator and std::ostream_iterator 
#include <algorithm> //for std::copy 

正如你可以看到現在,你可以把它們打印,這種慣用的解決方案不使用指針new,它也不使用cast

+1

哇,它工作得很好。非常感謝,非常感謝...... :) – lakshitha 2012-07-11 15:59:47

+1

先生,首先我必須感謝您的好意和幫助。他們對我非常有幫助。感謝idoms,我是編程新手。再次感謝......:D – lakshitha 2012-07-11 18:09:53

+0

好的。現在我成功創建了image.txt,第二步是使用它並創建圖像。首先我使用'stringstream ss'並得到了它的角色。我是這樣做的。 'ss <<(unsigned char)atoi(a)'。然後'unsigned char * s =(ss.str()).c_str()',現在需要將它寫入文件。 'ofstream file(「image2.jpg」,ios :: binary); 'fileo.write(S,的sizeof(S));' 。這就是我做到這一點,問題是它不會在第一個null之後寫入enything。所以輸出文件只有4個字節。那麼將它寫成一個binery文件的正確方法是什麼 – lakshitha 2012-07-12 15:17:46