从大文件创建直方图

时间:2019-01-17 22:05:38

标签: c

我有两个包含浮点型数据的大文件。我想使用两个文件创建一个直方图。但是,要访问256 ^ 3数据值,我尝试在C中使用嵌套的for循环,但由于分段错误而失败。

有没有一种我可以用来访问不会导致分段错误的数据值的方法?

这是我的代码:

int main () {

  int i,j,k,n_grid;
  float pc,mass_g,spat_res,vol_pix,max_vel,min_vel;
  float velocity,density,max;
  long start,index,index1,index2,counter,lSize,dim;
  FILE *p,*q;


  pc = 3.085677e-18;        //1 parsec in cm
  n_grid = 256;         //dimension of observed portion of input grid
  mass_g = 0.0;
  spat_res = pc*0.71/512;   //spatial resolution of grid in cm
  vol_pix = pow(spat_res,3);    //volume of each voxel in cm^3



  p = fopen("../dens_104/rho_052.dat","rb");
  q = fopen("../dens_104/velz.dat","rb");

  if (!p){
    printf("Unable to open dens file!");
      return 0;
    }
  else if (!q){
    printf("Unable to open the velx file!");
      return 0;
    }

  //obtain file size(s) 
  fseek(p,0,SEEK_END);
  lSize = ftell(p);
  rewind(p);

  dim = pow(lSize/sizeof(float),1.0/3.0);   //actual size of input grid


  max = 0;
  counter = 0;
  index = 0;
  while(fread(&density,sizeof(float),1,p),!feof(p) && !ferror(p)) {
    if(density > max) max = density,index = counter;
    counter += 1;
  }

  start = index - (pow(dim,2)+dim+1)*(n_grid/2-1);
  printf("Starting pixel value: %lu, Dimension of cube: %d\n",start, 
   (int)dim);
  printf("The maximum density is: %e with index: %lu \n", max,index); 

  rewind(p);
  fseek(p,start*sizeof(float),SEEK_SET);
  fseek(q,start*sizeof(float),SEEK_SET);

  max_vel = 0.0;
  min_vel = 0.0;
  index1 = 0;
  index2 = 0;


  while(fread(&velocity,sizeof(float),1,q),!feof(q) && !ferror(q)) {
    if(velocity > max_vel) max_vel = velocity,index1=counter;
    if(velocity < min_vel) min_vel = velocity,index2=counter;
     counter += 1;
  }


  printf("The maximum velocity is: %e with index: %lu\n", max_vel,index1); 
  printf("The minimum velocity is: %e with index: %lu\n", min_vel,index2);


  density = 0.;
  for (k=0;k<n_grid;k++){
    fseek(p,(start+k*dim*dim)*sizeof(float),SEEK_SET);
    for (j=0;j<n_grid;j++){
      fseek(p,(start+j*dim+k*dim*dim)*sizeof(float),SEEK_SET);
      for (i=0;i<n_grid;i++){
        fread(&density,sizeof(float),1,p);
        mass_g += density*vol_pix;
      }
    }
  }

  printf("The mass of the observed cube is: %e \n", mass_g); 

}

0 个答案:

没有答案