简体   繁体   中英

Reading and writing double precision from/to files

I am trying to write double arrays into files and read them again. Below is my code, but there is something I am missing. It sounds silly but I cannot get it right.

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

int main(){

  int i,j,k;
  int N = 10;

  double* readIn = new double[N];
  double* ref = new double[N];
  FILE* ptr1, *ptr2;

  ptr1 = fopen("output.txt","w");
  //write out
  for (i = 0; i < N;i++){
    ref[i] = (double)i;
    fprintf(ptr1,"%g\n",(double)i);
  }
  fclose(ptr1);
  //read file
  ptr2 = fopen("output.txt","r+");
  //read in
  for(i = 0;i < N;i++)
    fscanf(ptr2, "%g", &readIn[i]); 


  fclose(ptr2);

  for(i = 0;i<N;i++)
    if(ref[i] != readIn[i]){
      printf("Error:  %g   %g\n",ref[i], readIn[i]);
    }

  return 0;

}

Your fscanf is using the wrong format string (which GCC will tell you about if you enable sufficient warnings).

So your double is filled with float value, which of course leads to rather "random" errors.

If you change the "%g" to "%lg" , it should work just fine (at least it does on my Linux box).

Of course, if you use the C++ streams, eg

 #include <fstream>

 std::ofstream file1;
 std::ifstream file2;

 file1.open("output.txt");

 for (i = 0; i < N;i++){
    ref[i] = (double)i;
    file1 << (double)i << std::endl;
 }

and

   file2.open("output.txt");
   for(i = 0;i < N;i++)
      file2 >> readIn[i]; 

the whole problem would have been avoided - and if you edit the readIn variable to be float , as long as the values are valid for that, it would be possible to read those values without chaning anything else [assuming the output is also using cout instead of printf, of course].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM