【发布时间】:2014-09-22 08:15:29
【问题描述】:
#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 ................
但由于某种原因,它不会打印和十六进制第二、第三行....
【问题讨论】:
-
您要么需要在循环中调用
fgets,一次读取一行,要么使用fread,读取固定大小的块。