84 lines
2.0 KiB
C
84 lines
2.0 KiB
C
#include <stdio.h>
|
|
#include <unistd.h>
|
|
#include <fcntl.h>
|
|
#include <ctype.h>
|
|
#include <string.h>
|
|
#include <stdlib.h>
|
|
|
|
#define MAX_COLS 256
|
|
|
|
int main(int argc, char *argv[]) {
|
|
int fd = 0;
|
|
unsigned char buf[MAX_COLS];
|
|
|
|
int n;
|
|
unsigned int offset = 0;
|
|
|
|
int cols = 16;
|
|
char *filename = NULL;
|
|
|
|
for (int i = 1; i < argc; i++) {
|
|
if (strcmp(argv[i], "-l") == 0) {
|
|
if (i + 1 < argc) {
|
|
cols = atoi(argv[++i]);
|
|
if (cols <= 0 || cols > MAX_COLS) {
|
|
printf("xxd: invalid column length (1-%d)\n", MAX_COLS);
|
|
return 1;
|
|
}
|
|
} else {
|
|
printf("xxd: option -l requires an argument\n");
|
|
return 1;
|
|
}
|
|
} else {
|
|
filename = argv[i];
|
|
}
|
|
}
|
|
|
|
// 2. 파일 열기
|
|
if (filename != NULL) {
|
|
fd = open(filename, O_RDONLY);
|
|
if (fd < 0) {
|
|
perror("xxd");
|
|
return 1;
|
|
}
|
|
}
|
|
|
|
// 3. 읽기 및 출력 루프
|
|
// sizeof(buf)가 아니라 설정된 cols 만큼 읽어야 함
|
|
while ((n = read(fd, buf, cols)) > 0) {
|
|
|
|
// (1) 오프셋 출력
|
|
printf("%08x: ", offset);
|
|
|
|
// (2) Hex 데이터 출력
|
|
for (int i = 0; i < cols; i++) {
|
|
// 2바이트마다 그룹핑 (가독성)
|
|
if (i % 2 == 0) printf(" ");
|
|
|
|
if (i < n) {
|
|
// 데이터가 있으면 출력
|
|
printf("%02x", buf[i]);
|
|
} else {
|
|
// 데이터가 없으면 공백 채움 (Padding)
|
|
printf(" ");
|
|
}
|
|
}
|
|
|
|
printf(" ");
|
|
|
|
// (3) ASCII 문자 출력
|
|
for (int i = 0; i < n; i++) {
|
|
if (isprint(buf[i])) {
|
|
printf("%c", buf[i]);
|
|
} else {
|
|
printf(".");
|
|
}
|
|
}
|
|
|
|
printf("\n");
|
|
offset += n;
|
|
}
|
|
|
|
if (filename != NULL) close(fd);
|
|
return 0;
|
|
} |