gpt4 book ai didi

c - C语言的hexdump程序

转载 作者:太空宇宙 更新时间:2023-11-04 07:14:30 25 4
gpt4 key购买 nike

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 255

void hexDump (char *desc, void *addr, int len) {
int i;
unsigned char buffLine[17];
unsigned char *pc = (unsigned char*)addr;


if (desc != NULL){

printf ("%s:\n", desc);

}


for (i = 0; i < len; i++) {


if ((i % 16) == 0) {

if (i != 0)

printf (" %s\n", buffLine);
// if (buffLine[i]== '\0') break;

if (pc[i] == 0x00) exit(0);

// Prints the ADDRESS
printf (" %07x ", i);
}

// Prints the HEXCODES that represent each chars.
printf ("%02x", pc[i]);
if ((i % 2) == 1)
printf (" ");



if ((pc[i] < 0x20) || (pc[i] > 0x7e)){
buffLine[i % 16] = '.';
}

else{

buffLine[i % 16] = pc[i];

}


buffLine[(i % 16) + 1] = '\0'; //Clears the next array buffLine


}



while ((i % 16) != 0) {
printf (" ");
i++;
}


printf (" %s\n", buffLine);
}

//----------------------------------------------

int main()
{
FILE *ptr_file;
char buff[SIZE];

ptr_file =fopen("input.txt","r");
if (!ptr_file){
printf("returning 1");
return 1;
}

memset(buff, '\0', sizeof( buff) );
fgets(buff,SIZE, ptr_file);
hexDump ("buff", &buff, sizeof (buff));

fclose(ptr_file);

return 0;
}
//*/

抱歉,我是 C 的新手,所以现在有点乱,我一直在删除部分并制作临时代码等...所以无论如何,这是通过从 input.txt 中读取字符并通过在右侧打印十六进制表示和 Acii 表示来输出的。对于形成不可打印字符的字节,打印一个“.”字符(一个点/句点字符,即十六进制值 2E)。:

0003540: 0504 0675 6e73 6967 6e65 6420 6368 6172 ...unsigned char
0003550: 0008 0107 0000 0131 0675 6e73 6967 6e65 .......1.unsigne

但我的程序不打印文本中“新行”以外的任何内容。例如:在我的 input.txt 中,我有:

This is line 1 so this will be longer than usual
line 2 is this
this is the last line

看完我的程序后,它只输出这样的:

  0000000 5468 6973 2069 7320 6c69 6e65 2031 2073   This is line 1 s
0000010 6f20 7468 6973 2077 696c 6c20 6265 206c o this will be l
0000020 6f6e 6765 7220 7468 616e 2075 7375 616c onger than usual
0000030 0a00 0000 0000 0000 0000 0000 0000 0000 ................

但由于某些原因,它不会在第二行、第三行打印和十六进制....

最佳答案

您应该使用fread() 来读取文件,并将其放入一个循环中(直到它返回0),以便它读取整个文件。如果您在 Windows 上,还请确保使用“rb”(二进制模式)打开文件,而在 Unix 上则无关紧要。

最后一个建议是使用 isascii() 或其姊妹函数之一,而不是手动检查“可打印性”。参见 http://linux.die.net/man/3/isalnum .

关于c - C语言的hexdump程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25969466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com