C++ fwrite , ferror code 36 Broken Pipie

366 views Asked by At

I have a problem with saving lot of data to binary file in c++ , i'm using CodeBlocks

My code:

long tablica[10000];
int main(int argc, char *argv[])
 {
  FILE * pFile;
  clock_t start,stop;
  srand (time(NULL));
  long i;
  for(i=0;i<10000;i++){
                 tablica[i] = rand() % 100000;
                 }
  start = clock();
  pFile = fopen ("myfile.bin","wb");
  if (pFile!=NULL)
   {
    long test = fwrite(tablica,sizeof(long),sizeof(tablica),pFile);
    int err = ferror(pFile);
    fclose(pFile);
    printf("%d",err);
   }
    double wynik;
    wynik = double(stop-start);
    printf("\n %f",wynik);
return 0;
}

It just rand lots of data , and save it to file.

Strange thing is that when compiling and running it from DEBUG profile it runs well , and when running from release it trows error num 32 Broken Pipe

I went to build options , and it seems that Produce debbuging symbols makes the diffrence , when it's on file write is sucessfull ,and if it's off i get brokenpipe.

Can some1 tell why this problem occurs and how to remove it. I need my app to be quite fast and i guess that produce debbuging symbols will slow it down.

1

There are 1 answers

8
Dan Korn On BEST ANSWER

The problem is here:

long test = fwrite(tablica,sizeof(long),sizeof(tablica),pFile);

Calling sizeof on an array returns the size of the array in bytes, not the number of elements, as explained here: How do I determine the size of my array in C?

So you're telling fwrite to write 40000 longs, not 10000 longs.

The reason it works in debug mode but not release is probably due to checks in the debug runtime. (Though you don't specify what platform/compiler/runtime you're using, so it's hard to say for sure.)

I would fix it like so:

long test = fwrite(tablica,1,sizeof(tablica),pFile);

And you really should be checking that "test" return value.

Also, instead of trying to write all the data in one shot, I would make a series of fwrite calls in a loop, writing, say, a kilobyte (1024 bytes) at a time.