读取C语言struct生成的数据文件
Python代码,读取tostruct.dat中的结构体数据,并以tuple的形式打印出来
# -*- coding: cp936 -*-
'''读取C语言struct生成数据文件'''
import struct
import cStringIO
'''
步距长度计算,查看C语言字节对齐内容
typedef struct _CToStruct
{
char c;
short h;
int i;
}CToSturct;
sizeof(c) = 1
pad = 1
sizeof(h) = 2
sizeof(i) = 4
struct_size = 8
'''
struct_size = 8
fp = file("c:\\tostruct.dat","rb")
import os
import mmap
# 一次性将全部数据读入内存
data = fp.read()
for i in range(0,os.path.getsize("C:\\tostruct.dat"),8):
# 每次移动8个字节
print struct.unpack('Bhi',data[i:i+8])
fp.close()
C语言生成以结构体为单元的数据文件。
#include stdio.h>
typedef struct _CToStruct
{
char c;
short h;
int i;
}CToSturct;
#define TS_SIZE (5)
//½«½á¹¹ÌåÊý¾ÝдÈëÎļþ
int writeToFile(void* pData,unsigned int size)
{
FILE* fp = fopen("c:\\tostruct.dat","wb");
if(fp == NULL)
return 0;
fwrite(pData,1,size,fp);
fclose(fp);
return 1;
}
int main(int argc, char* argv[])
{
int i = 0;
CToSturct ts[TS_SIZE] = {0};
for(;i TS_SIZE;i++)
{
ts.c = (char)i;
ts.h = (short)i * i;
ts.i = i* i * i;
}
writeToFile(ts,sizeof(ts));
return 0;
}