2016-06-20 5 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++ 방법을 사용하여 파일 스트림을 기반으로 : fstream, ifstream, ofstream, wfstream

바이너리 모드 (그리고 텍스트 모드)는 플래그 std::ios::binary를 사용해야에서 엽니 다.

예를 들어, 당신은 다음과 같은 방법으로

#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 파일 (한 번에 하나 개의 문자를) 읽을 수 있습니다 : 내 나쁜 영어

관련 문제