写入C中的多个文件

时间:2014-03-28 10:19:59

标签: c

我有以下代码。我正在尝试创建5776个文件,但代码以分段错误结束。故障发生时,它只会产生1000或更多。我尝试了20,30等的值代替76以下的数字,即方形低于1000且程序执行良好的数字。任何想法......?

#include <stdio.h> 
#include <stdlib.h>
#include <math.h>

// Entry point for the program
int main () {
// Define the variables
   float density,dim,max,temp,curr;
   long lSize, counter, index, count, start;
   FILE *oFile, *pFile, *qFile, *fp;
   int i,j,k,sub;

const int maxSize=13;

char file[] = "file";
char Filename[maxSize];

// Open the input density file
pFile = fopen("core1_dens_0107.bin","rb");
qFile = fopen("core1_temp_0107.bin","rb");

if (pFile == NULL) { printf("Unable to open density file!"); exit(1); }

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

dim = pow(lSize/sizeof(float),1.0/3.0);

printf( "File size : %lu Bits \n", lSize );

// Open file in write mode to write density records in ASCII format
oFile = fopen( "results_temp.dat", "w" );
if (oFile == NULL) { printf("Unable to open output results file!"); exit(1); }

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

sub = 256;
start = index-(pow(dim,2)+dim+1)*(sub/2-1);

curr = index+dim*90+90;
count = 0;

for(k=0;k<76;k++){
  for(j=0;j<76;j++){
curr = curr+j+k*(dim-76);
sprintf(Filename,"%s_%d.txt",file,count);
fp=fopen(Filename,"w");
for(i=0;i<256;i++){

  fseek(qFile,(curr+i*dim*dim)*sizeof(float),SEEK_SET);
  fprintf(oFile,"%f\n",curr+i*dim*dim);
  fread(&temp,sizeof(float),1,qFile);

  fprintf(fp,"%5.2f\n",temp);
}
count++;
  }
}


printf( "No. of Files : %lu \n", count );


// Close both input and output files
fclose(oFile);
fclose(pFile);
fclose(qFile);

return 0;
}

0 个答案:

没有答案