Reading data is not same as text file data after using Fread()

i trying to read the text file data using fread(),but the reading data is not same as the text file data.


1
2
3
4
5
6
7
8
text file data:
0
0.23
1.276
5.387
.
.
.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include"stdio.h"
 int main()
 {
   double x[100];
 FILE*f=fopen("mytextfile.txt","r");
  fseek(f,SEEK_SET,0);
  fread(x,sizeof(x),1,f);
  for(int i=0;i<101;i++)
  {
    cout<<x[i];
  }
   return 0;
  }


1
2
3
4
5
6
Output
2.345e-23
1.23e-65
7.2334e-56
.
.
Last edited on
The answer is in your question: your file contains text data. fread reads binary data.
Use fscanf in a loop to extract text representation of floating point numbers and store it in your doubles array.
1
2
3
4
5
6
7
8
9
10
11
  double x[100];
 FILE*f=fopen("mytextfile.txt","r");
  fseek(f,SEEK_SET,0);
 
  for(int i=0;i<101;i++)
  {
      fscanf(f,"%g",x);
      cout<<x[i];
  } 

return 0;


now also the output is different.....
you are
1) writing everything in first array element
2) writing floats instead of doubles
3) looping 101 times for array with 100 elements.

Is there any reason you use C i/O instead of C++ one?
Topic archived. No new replies allowed.