Nov 6, 2015 at 4:18pm UTC
I used the following code.
I can read the files successfully but the In.fail(); gives true value after read function(Line 24).
So please help me to decode why the fail function returns true value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#include<fstream.h>
#include<iostream.h>
#include<conio.h>
#include<process.h>
#include<stdio.h>
#include<string.h>
struct Initial
{
char Name[25];
char Password[25];
char NOC[25];
};
void main()
{
Initial J;
clrscr();
ifstream In("Initial.dat" );
if (In.fail())
cout<<"Fail" ;
In.read((char *)&J,sizeof (J));
if (In.fail())
cout<<"Fail" ;
cout<<"\n\nyour Name : " ;
puts(J.Name);
cout<<"\nthe Password : " ;
puts(J.Password);
In.close();
if (In.fail())
cout<<"Fail" ;
getch();
}
Last edited on Nov 6, 2015 at 4:20pm UTC
Nov 6, 2015 at 7:15pm UTC
- You shouldn't be reading a structure all at once, its wrong because of a few reasons. You should read in members of the structure one by one.
- dont use char arrays, use std::string, and everything will be easier
Nov 6, 2015 at 7:16pm UTC
If you are reading the entire structure from a file, then you need to specify sizeof J, instead of sizeof 3.
Nov 11, 2015 at 1:00pm UTC
IT is sizeof J.
and As in my Text Book(12th class), the method provided to read from binary file is this only(whole struct or class at once).
What is other method(''use std::string'' ????).
Nov 11, 2015 at 2:13pm UTC
Sorry, I must have mis-read that: I thought it said 3, not J. Your code should work. How was the file written?
Nov 11, 2015 at 3:47pm UTC
If you're treating a file as a binary stream, open it in binary mode.
ifstream In("Initial.dat" , std::ios::binary);