C_C++

(C언어) 텍스트 파일을 문자와 16진수로 출력하는 코드 hexdump.c

고니자니 2025. 4. 9. 10:31
반응형

아래는 C언어로 작성된 프로그램으로, 주어진 텍스트 파일을 열어 파일의 내용을 문자와 16진수(hexdump) 형태로 출력합니다. 이 프로그램은 바이너리 파일도 처리할 수 있습니다.

#include <stdio.h>
#include <stdlib.h>

void print_hex_ascii_line(const unsigned char *data, int length, int offset) {
    int i;

    // Offset
    printf("%08x  ", offset);

    // Hex part
    for (i = 0; i < 16; i++) {
        if (i < length)
            printf("%02x ", data[i]);
        else
            printf("   ");
        if (i == 7) printf(" ");
    }

    printf(" ");

    // ASCII part
    for (i = 0; i < length; i++) {
        if (data[i] >= 32 && data[i] <= 126)
            printf("%c", data[i]);
        else
            printf(".");
    }

    printf("\n");
}

int main(int argc, char *argv[]) {
    FILE *file;
    unsigned char buffer[16];
    size_t bytesRead;
    int offset = 0;

    if (argc != 2) {
        fprintf(stderr, "사용법: %s <파일이름>\n", argv[0]);
        return 1;
    }

    file = fopen(argv[1], "rb");
    if (file == NULL) {
        perror("파일을 열 수 없습니다");
        return 1;
    }

    while ((bytesRead = fread(buffer, 1, sizeof(buffer), file)) > 0) {
        print_hex_ascii_line(buffer, bytesRead, offset);
        offset += bytesRead;
    }

    fclose(file);
    return 0;
}

 

사용 방법:

1. 위 코드를 예를 들어 hexdump.c라는 파일에 저장합니다.

2. 터미널에서 컴파일합니다:

gcc -o hexdump hexdump.c

 

3. 프로그램을 실행합니다:

./hexdump example.txt

hexadump.c

출력 예시:

00000000    48 65 6c 6c 6f 2c 20 43 21 0a                                          Hello, C!.
 

이 프로그램은 xxd나 hexdump 명령어처럼 간단한 분석용으로 사용할 수 있어요. 필요에 따라 출력 포맷을 조정할 수도 있습니다.

 

반응형