Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This code should take 3 decimal places from the user and in the binary file
Write then read it, but it does not save anything in the file and does not give errors
What is the problem with writing to a file?

What I have tried:

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
 float num;
 streampos size;
 fstream outputFile;
 char* mem;
 //write from file
  outputFile.open("output.bin", ios::out | ios::app|ios::binary);
  
 for (int i = 0; i < 3; i++)
 {
 
 cout << "Enter float number : ";
 cin >> num;
 cout << endl;
 
 outputFile.write(mem,size );
 
 }
 outputFile.close();
 
 //read from file
  outputFile.open("output.bin", ios::ate | ios::binary);
  if(outputFile.is_open())
  {
      size=outputFile.tellg();
      
      char* mem=new char [size ];
      outputFile.seekg(size,ios::beg);
      outputFile.read(mem,size);
      
        }
outputFile.close();
 return 0;
}
Posted
Updated 26-Jul-21 10:05am
Comments
Greg Utas 27-Jul-21 18:19pm    
Also see the comment below my post.

1 solution

If you read your code closely, you would see that you read from cin into num but write some totally unrelated thing (mem) to the file.
 
Share this answer
 
Comments
merano99 27-Jul-21 18:10pm    
You should add ios :: in as you read.
myfile.open(filename, ios::in | ios::ate | ios::binary);
Greg Utas 27-Jul-21 18:21pm    
Good point, so I told OP about it in a comment above.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900