讀取bin文件,並且按結構體賦值打印
阿新 • • 發佈:2018-12-03
tails net content nbsp mat was 思路 進行 讀取
目標:讀取一個bin文件,並且將bin文件中的數據,按字節對齊賦值給結構體,並且打印出結構體的內容
目前思路是簡單的先將bin文件數據一次性讀到一個數組中,再將數組強制轉換為結構體
char buff[256] FILE *fp; fp = NULL; fp = fopen(argv[1], "rb"); if (NULL == fp) { printf( "The file was not opened\n"); return; } fread(buff, 1, 256, fp); structA a = (struct A) buff;
另外,在博客看到一個輸出結構體的demo,貼在這裏
只需要傳入要打印結構體的結構體指針和結構體大小,就可以進行打印,且可以控制一行打印的字節數和字節與字節之間是否需要留一個空格
void print_struct_content(void *strp, size_t size) { size_t i; char *printbit = (char *)strp; int format = 0; for (i = 0; i < size; i++) { printf("%02x", printbit[i]&0XFF); format++; if (0 == (format % 4)) { printf("\n"); } } }
參考:
https://blog.csdn.net/XIAXIA__/article/details/9360149
讀取bin文件,並且按結構體賦值打印