博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

数据输出十六进制格式

Posted on 2011-12-23 16:07  ccmfc  阅读(1137)  评论(0编辑  收藏  举报

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

#define MAX_PATH 256

int strch_index_r(const char *str, const char ch)
{
char *tmp=(char*)str+strlen(str)-1;

while(tmp!=str && *tmp!=ch && tmp--);

return tmp-str;
}

int data_file_size(const char *path)
{
int ret=0;
FILE *read=NULL;

read=fopen(path, "rb");
if(!read)return 0;
fseek(read, 0, SEEK_END);
ret=ftell(read);
fclose(read);

return ret;
}

int data_read(const char *path, char *buf, const int size, int* out)
{
int ret=0;
FILE *read=NULL;

if(!path || !buf || size<=0)return 0;

read=fopen(path, "rb");
if(!read)return 0;

ret=fread(buf, 1, size, read);
fclose(read);

if(out)*out=ret;

return ret;
}

char* ch2hex(const unsigned char ch, char *dest)
{
int tmp=0;

if(ch<16)
{
*dest='0';
if(ch>9)
*(dest+1)='A'+ch-10;
else
*(dest+1)='0'+ch;
}
else
{
tmp=ch/16;
if(tmp>9)
*dest='A'+tmp-10;
else
*dest='0'+tmp;
tmp=ch%16;
if(tmp>9)
*(dest+1)='A'+tmp-10;
else
*(dest+1)='0'+tmp;
}

return dest;
}

int data_write_hex(const char *path, const char *buf, int size, const char *symbol)
{
int ret=0;
char bol[16]={0};
char hex[3]={0};
FILE *write=NULL;
int line=size>16?16:size;
char flags=0;

if(!path || !buf || size<0)return 0;

if(symbol)strcpy(bol,symbol);

do
{
write=fopen(path, "w");
if(!write)break;
if(size==0)break;

while(ret<size-1)
{
ch2hex(*(buf+ret), hex);

// if(flags&&flags%(line-1)==0)fprintf(write, "%s%s", "0x", hex);
if(flags&&flags%line==0){fprintf(write,"%s","\n");flags=-1;}
else fprintf(write, "%s%s%s", "0x", hex,bol);
flags++;
ret++;
}
ch2hex(*(buf+ret), hex);
fprintf(write, "%s%s", "0x", hex);
} while (0);

if(write)fclose(write);

return ret;
}

int data_hex_file(const char* spath, const char* dpath, const char* symbol)
{
int ret=0;
int size=data_file_size(spath);
char *buf=NULL;
char *path;

if(dpath)
{
int len=strlen(dpath)+5;
path=(char*)malloc(len);
strcpy(path, dpath);
}
else
{
int len=strlen(spath)+5;
path=(char*)malloc(len);
memset(path, 0, len);
strncpy(path, spath, strch_index_r(spath, '.'));
strcat(path, ".hex");
}

buf=(char*)malloc(size);
if(!buf)return 0;

data_read(spath, buf, size, NULL);
ret=data_write_hex(path, buf, size, symbol);

if(buf){free(buf);buf=NULL;}
if(path){free(path);path=NULL;}

return ret;
}

void data_handle(int num, char ** ppobj)
{
char path[MAX_PATH]={0};
char file[MAX_PATH]="mm_logo.jpg";

printf("ÇëÊäÈëÎļþÃû:");
gets(file);

strncpy(path, *ppobj, strch_index_r(*ppobj, '\\')+1);
strcat(path,file);
data_hex_file(path, NULL, ", ");
}

int main(int argc, char **argv)
{
data_handle(argc, argv);

// printf("%d\n", '9');
return 0;
}