2015-10-13 58 views
3

我試圖輸出這個.exe文件的純文本內容。它裏面有明文內容,就像「以這種方式更改代碼不會影響優化代碼的質量」。微軟將所有東西放入.exe文件中。當我運行下面的代碼時,我得到M Z E的輸出,然後是心臟和鑽石。我究竟做錯了什麼?試圖輸出exe文件中的所有內容

ifstream file; 
char inputCharacter;  

file.open("test.exe", ios::binary); 

while ((inputCharacter = file.get()) != EOF) 
{ 

    cout << inputCharacter << "\n";  
} 


file.close(); 

回答

4

我會使用類似std::isprint的東西來確保在打印之前該字符是可打印的,而不是一些奇怪的控制代碼。

事情是這樣的:

#include <cctype> 
#include <fstream> 
#include <iostream> 

int main() 
{ 
    std::ifstream file("test.exe", std::ios::binary); 

    char c; 
    while(file.get(c)) // don't loop on EOF 
    { 
     if(std::isprint(c)) // check if is printable 
      std::cout << c; 
    } 
} 
3

您已經打開二進制流,這對於預期目的是有益的。但是,您按原樣打印每個二進制數據:其中一些字符不可打印,輸出奇怪。

潛在的解決方案:

如果您想打印一個exe的內容,你會得到更多的非打印字符打印相比的。所以一個方法可以是打印的十六進制值,而不是:

while (file.get(inputCharacter)) 
{ 
    cout << setw(2) << setfill('0') << hex << (int)(inputCharacter&0xff) << "\n";  
} 

或者你可以使用顯示的十六進制值的調試方法,然後顯示字符,如果是打印或「」如果不是:

while (file.get(inputCharacter)) { 
    cout << setw(2) << setfill('0') << hex << (int)(inputCharacter&0xff)<<" "; 
    if (isprint(inputCharacter & 0xff)) 
     cout << inputCharacter << "\n"; 
    else cout << ".\n"; 
} 

那麼,對於人機工程學的緣故,如果exe文件中包含任何實際的exe,你最好選擇對每行;-)顯示幾個字符

2

二進制文件是一個字節集合。字節的取值範圍爲0..255。可以安全「打印」的可打印字符形成的範圍要窄得多。假設最基本的ASCII編碼

  • 32..63
  • 64..95
  • 96..126
  • 加,也許,有的高於128,如果你的代碼頁有他們

參見ascii table

超出此範圍的可能,至少每個人的性格:

  • 打印出隱形
  • 打印出一些奇怪的垃圾
  • 成爲事實,將改變的設置控制字符您的終端

某些終端支持「文本結束」字符,並且只會在以後停止打印任何文本。也許你打了那個。

我想說,如果您只對文本感興趣,那麼只會打印該printables並忽略其他人。或者,如果你想要一切,那麼也許用十六進制形式寫出來呢?

0

這工作:

ifstream file; 
char inputCharacter; 
string Result; 

file.open("test.exe", ios::binary); 

while (file.get(inputCharacter)) 
{  
    if ((inputCharacter > 31) && (inputCharacter < 127)) 
     Result += inputCharacter;  
} 

cout << Result << endl; 
cout << "These are the ascii characters in the exe file" << endl; 
file.close();