[AWK] C struct to fprintf script

example code

#!/bin/bash

awk ' { if ($1 == "u_int" ) FORMAT="%u"; \
else if ($1 == "u_short" ) FORMAT="%u"; \
else if ($1 == "uint64_t" ) FORMAT="%lu"; \
else if ($1 == "int" ) FORMAT="%d"; \
else if ($1 == "int32_t" ) FORMAT="%d"; \
else if ($1 == "int64_t" ) FORMAT="%ld"; \
else if ($1 == "u_char" ) FORMAT="%s"; \
else if ($1 == "char" ) FORMAT="%s"; \
else FORMAT="ERROR"; \
if ( substr($2,length($2),1) == ";" ) KEY=substr($2,0, length($2)-1);
else KEY=$2; \
print "fprintf(stdout, \"" KEY "= [" FORMAT "]\\n\", p_x->" KEY " );" } ' a.dat


# a.dat
typedef struct {
      u_int    m1;
      int myport;
      u_short  ushort2;
      u_int    int1;
      u_short  data;
      u_char   dummy[8];
      uint64_t length;
      char kkk       [  1 + 1];
} my_struct;

# output
fprintf(stdout, "struct= [ERROR]\n", p_x->struct );
fprintf(stdout, "m1= [%u]\n", p_x->m1 );
fprintf(stdout, "myport= [%d]\n", p_x->myport );
fprintf(stdout, "ushort2= [%u]\n", p_x->ushort2 );
fprintf(stdout, "int1= [%u]\n", p_x->int1 );
fprintf(stdout, "data= [%u]\n", p_x->data );
fprintf(stdout, "dummy[8]= [%s]\n", p_x->dummy[8] );
fprintf(stdout, "length= [%lu]\n", p_x->length );
fprintf(stdout, "kkk= [%s]\n", p_x->kkk );
fprintf(stdout, "my_struct= [ERROR]\n", p_x->my_struct );


# To-do
 1. support pointer
 2. add types
 3. "unsigned int" ....

Comments

Popular posts from this blog

e1000e 0000:00:1f.6 eno1: Detected Hardware Unit Hang

[WordPress] Change https redirect in DB.

sanitize on in CMakeLists.txt