1

I am writing binary file with the following code in FORTRAN:

Character(50) S
Real*8 A
A = 25.002  
OPEN(1,file='data.bin', access='stream',action='write') 
WRITE (1) A        
CLOSE(1)

And trying to read that with the following code in C++:

ifstream::pos_type size;
char * memblock

ifstream file ("data.bin", ios::in|ios::binary|ios::ate);
if (file.is_open())
{
  size = file.tellg();
  memblock = new char [size];
  file.seekg (0, ios::beg);
  file.read (memblock, size);
  file.close();

  delete[] memblock;
}

But it does not work! The second code can not read the file created by the first code. Any help appreciated!

VecTor
  • 83
  • 3
  • 13
  • How do you know it can't read the file? There's nothing in the code you show that even checks. – Mark Ransom Mar 28 '13 at 16:43
  • 1
    "it does not work" doesn't define the problem. HOW does it not work is required. Also, you don't have any error checking on your `new char` nor on your file.read (so you don't know why it's failing) – KevinDTimm Mar 28 '13 at 16:44
  • 1
    Does it not work because it doesn't read any data, or does it not work because it doesn't read the data you expect. Help us out! More information! Less exclamation marks! – john Mar 28 '13 at 16:45
  • It does not read any data. It gives zero size for the file! – VecTor Mar 28 '13 at 16:59

2 Answers2

1

file.tellg gives the current position. When you open the file, the position is 0. To fined the size of the file, first seek to the end, then do tellg.

stark
  • 12,615
  • 3
  • 33
  • 50
1

Problem Solved:

ifstream file ("data.bin", ios::in|ios::binary);
if (file.is_open())
{     
  double a = 0;
  file.read ((char*)&a,sizeof(double));
  file.close();    
}
VecTor
  • 83
  • 3
  • 13