我必须使用用C编写的程序,以这种方式从二进制文件中读取数据
nCnt = 0;
for (i=0;i<h.nsph;++i) {
fread(&gp,sizeof(struct gas_particle),1,fp);
if (bGas) {
kd->p[nCnt].iOrder = nCnt;
for (j=0;j<3;++j) kd->p[nCnt].r[j] = gp.pos[j];
++nCnt;
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码不是我正在使用的程序的整个代码,而只是与我的问题相关的部分.我需要读取nCnt粒子的位置,即每个粒子的坐标.我在python数组中有这些位置,看起来像这样
pos=array([[[ 0.4786236 , 0.49046784, 0.48877147],
[ 0.47862025, 0.49042325, 0.48877267],
[ 0.47862737, 0.49039413, 0.4887735 ],
...,
[ 0.4785084 , 0.49032556, 0.48860968],
[ 0.47849332, 0.49041115, 0.48877266],
[ 0.47849161, 0.49041022, 0.48877176]]])
Run Code Online (Sandbox Code Playgroud)
我应该如何在二进制文件中编写此数组,以便C代码可以正常读取?
使用python模块array和tofile()方法以C可以读取的格式写入数据,如果使用numpy 则以IO例程写入数据.
使用位数,'f'格式(浮点数)应该有效.
在C中,您可以像这样读取每一行:
float values[3];
fread( values, sizeof( float ), 3, fh );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3977 次 |
| 最近记录: |