Fail But No Fail

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
- 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
If you are reading the entire structure from a file, then you need to specify sizeof J, instead of sizeof 3.
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'' ????).
Sorry, I must have mis-read that: I thought it said 3, not J. Your code should work. How was the file written?
If you're treating a file as a binary stream, open it in binary mode.

ifstream In("Initial.dat", std::ios::binary);
Topic archived. No new replies allowed.