[英]Having trouble with hexdump program in C
I can't seem to get any characters to print, in fact, it seems like the program won't read any file correctly, as all the hex values are zeros when I give it a file. 我似乎无法打印任何字符,实际上,该程序似乎无法正确读取任何文件,因为当我给它一个文件时,所有十六进制值均为零。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <argp.h>
#include <sys/types.h>
#include <sys/stat.h>
static error_t parse_opt(int key, char *arg, struct argp_state *state);
static void dump_hex(char *f, size_t l);
static struct argp_option options[] = {
{"filepath", 'f', "PATH", 0, "uses filepath provided by user" },
{ 0 }
};
struct arguments {
char *path;
/* int *column_size; */
};
static error_t parse_opt(int key, char *arg, struct argp_state *state) {
struct arguments *arguments = state->input;
switch(key) {
case 'f':
arguments->path = arg;
break;
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}
static struct argp argp = { options, parse_opt, NULL, NULL };
static void dump_hex(char *f, size_t l) {
FILE *fd;
size_t i;
unsigned char *b = (unsigned char *)malloc(16 * sizeof(unsigned char));
memset(b, 0, 16 * sizeof(unsigned char));
if((fd = fopen(f, "r"))) {
for(i = 0; i <= l; i++) {
if((i % 8) == 0) {
if(i != 0) {
printf("| %s\n", b);
}
/* print the offset */
printf("%05lx: ", i);
}
/* check if ASCII is printable */
b[i % 16] = isprint(b[i]) ? b[i] : '.';
/* print ASCII */
printf("%02x ", b[i]);
}
/* print remaining ASCII */
printf("| %s\n", b);
}
fclose(fd);
free(b);
}
int main(int argc, char *argv[]) {
struct arguments arguments;
struct stat sb;
off_t size;
arguments.path = "-";
argp_parse(&argp, argc, argv, 0, 0, &arguments);
stat(arguments.path, &sb);
size = sb.st_size;
dump_hex(arguments.path, size);
return 0;
}
Here is the output I receive upon giving it an argument to a binary: 这是给二进制参数提供的输出:
./hexdump --filepath=/tmp/a.out
212d0: 00 00 00 00 00 00 00 00 | ................
212d8: 00 00 00 00 00 00 00 00 | ................
212e0: 00 00 00 00 00 00 00 00 | ................
212e8: 00 00 00 00 00 00 00 00 | ................
212f0: 00 00 00 00 00 00 00 00 | ................
212f8: 00 00 00 00 00 00 00 00 | ................
Segmentation fault
Also, any tips on making the code a bit more concise would be very beneficial. 而且,使代码更简洁的任何提示都是非常有益的。
The reason why you are getting zeros is that you don't read the content of your file and b
is initialized with 0x00
. 之所以得到零,是因为您不读取文件的内容,并且
b
用0x00
初始化。 Your just opening and closing the file. 您只需打开和关闭文件。
Another problem (this could be the reason for the segmentation fault) is that b
has a size of 16 bytes. 另一个问题(这可能是分段错误的原因)是
b
的大小为16个字节。 On some places you are using i % 16
but not on all (on some places you use i
directly). 在某些地方,您使用的是
i % 16
但不是全部使用(在某些地方,您直接使用i
)。 You should definitely check this. 您绝对应该检查一下。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.