xxd.h
#ifndef ANALYZER_XXD_H
#define ANALYZER_XXD_H
#ifdef __cplusplus
extern "C" {
#endif
#include /* getenv */
typedef unsigned char byte;
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef void (*sFn_t)(byte *s, uint8_t len, void *pn);
/* log文件大于1M之后改名为 debug.log-bak, 重新写入debug.log */
#define bcl_debug(fmt, ...) \
do { \
char path[255]; \
long fl = 0; \
snprintf(path, 255, "%s/log/debug.log", getenv("FAPWORKDIR")); \
FILE *fp = fopen(path, "a"); \
fl = ftell(fp); \
if (fl > 1048576) { \
fclose(fp); \
char npath[255]; \
strcpy(npath, path); strcat(npath, "-bak"); \
rename(path, npath); \
fp = fopen(path, "w"); \
} \
fprintf(fp, fmt, ##__VA_ARGS__); \
fclose(fp); \
} while (0); \
int readFromFile(const char *path, sFn_t fn, void *pn);
void xxd(byte *s, uint8_t len, void *param);
#ifdef __cplusplus
}
#endif
#endif //ANALYZER_XXD_H
* xxd.c
#include "xxd.h"
#include /* FILE */
#include /* strncmp, memset */
#include /* errno */
int readFromFile(const char *path, sFn_t fn, void *pn) {
FILE *fp = NULL;
if (0 == strncmp(path, "stdin", 5)) {
fp = stdin;
} else {
fp = fopen(path, "r");
if (NULL == fp) {
fprintf(stderr, "ERROR(%d) open %s: %s", errno, path, strerror(errno));
return errno;
}
}
byte buf[16];
size_t br = 0;
while (!feof(fp)) {
memset(buf, 0, 16);
br = fread(buf, sizeof(byte), 16, fp);
if (br < 1) {break;}
fn(buf, br, pn);
}
fclose(fp);
return 0;
}
void xxd(byte *s, uint8_t len, void *param) {
uint8_t i;
uint16_t *line = (uint16_t *)param;
fprintf(stdout, "%08x:", *line << 4);
for (i = 0; i+2 < len; i+=2) {
fprintf(stdout, " %02x%02x", s[i], s[i+1]);
}
if (i 0x7e) {
fputc('.', stdout);
} else {
fputc(s[i], stdout);
}
}
fputs("\r\n", stdout);
*line += 1;
}
* main.cpp
#ifdef __cplusplus
extern "C" {
#endif
#include
#include "xxd.h"
int main(int argc, char *argv[])
{
char sIn[255];
if (argc < 2) {
strcpy(sIn, "stdin");
} else {
strncpy(sIn, argv[1], 255);
}
uint16_t line = 0;
readFromFile(sIn, xxd, &line);
}
#ifdef __cplusplus
};
#endif
* CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(analyzer)
set(CMAKE_CXX_STANDARD 11)
add_executable(xxd main.cpp xxd.c xxd.h)
配置环境变量FAPWORKDIR,为了记录日志
Makefile
CC=cc
CFLAGS=-g -Wextra -O2 -fPIC -std=c99
SHLIBLDOPT=-shared -fPIC
AROPT=-curv
BINDIR=
APPBINDIR=
TOOLBINDIR=${FAPWORKDIR}/tbin
OBJ=xxd
TARGETS=${OBJ}
.c.o:
${CC} ${CFLAGS} -c $< -o $@
all: ${TARGETS}
clean:
rm -f ${OBJ}.o ${TARGETS}
install:
cp ${OBJ} ${TOOLBINDIR}/${OBJ}
uninstall:
rm -f ${TOOLBINDIR}/${OBJ}