2016-06-20 7 views
0

ファイル(jpg、txt、zip、cpp、...)をバイナリファイルとして開くにはどうすればいいですか?私は、通常、そのファイル形式を解釈するプログラムによってフォーマットされる前に、バイトを見たいと思っています。 可能でしょうか? C++でどうすればいいですか?おかげさまで 任意のファイルをバイナリファイルとして開きます

答えて

1

あなたがそうする機能をPOSIX使用(C道をしかし++ Cで動作する)ことができます。

#include <sys/types.h> 
#include <sys/stat.h> 
#include <fcntl.h> 
#include <unistd.h> 

int fd = open("file.bin", O_RDONLY); //Opens the file 
if(fd<0){ 
    perror("Error opening the file"); 
    exit(1); 
} 
char buf[1024]; 
int i; 
ssize_t rd; 
for(;;){ 
    rd = read(fd, buf, 1024); 
    if(rd==-1) //Handle error as we did for open 
    if(rd==0) break; 
    for(i = 0; i < rd; i++) 
    printf("%x ", buf[i]); //This will print the hex value of the byte 
    printf("\n"); 
} 
close(fd); 
+0

'読んで()' 'を返しますssize_t'のため申し訳ありませんが、 'int'ではなく。 –

+0

あなたは正しいです、 – Omar

+0

@Omar - C++では、標準のansi-C 'fopen()'インタフェースを使うこともできます – max66

0

あなたは古いCインタフェース(fopen()、など)が、C++の方法を使用することができ、ファイル・ストリームに基づいています:などfstreamifstreamofstreamwfstream

バイナリモード(およびないテキストモード)で開くには、あなたはフラグstd::ios::binaryを使用する必要があります。以下の方法で

例では、あなたは(一度に1文字)のファイルを読むことができます

#include <fstream> 
#include <iostream> 

int main() 
{ 
    char ch; 

    std::ifstream fl("file.log", std::ios::binary); 

    while (fl.read(&ch, sizeof(ch))) 
     std::cout << "-- [" << int(ch) << "]" << std::endl; 

    return 0; 
} 

PS:私の悪い英語

関連する問題