I want to know that how many Student class objects in a file.
plz help me out.
Below is a class of Students and 2 function for read and write object in a file, in read function

while(in.eof()!= 1){
		in.read((char *)&st,sizeof(st));

st.showData(); always show the last object twise.. unable to sort out my mistake in the code.

#include <iostream>
#include <conio.h>
#include <fstream>
#include <string.h>
using namespace std;

class Student{
	char name[30];
	int id;
	int rollNo;

	Student(char *n,int i, int r){
		id = i;
		rollNo = r;
	void getData(){
		cout << "Enter Name    : "; cin >> name;
		cout << "Enter Id      : "; cin >> id;
		cout << "Enter Roll No : "; cin>> rollNo;

	void showData(){
		cout << "Student Detail---------------"<<endl;
		cout << "Name      : " << name << endl;
		cout << "Id Number : " <<id << endl;
		cout << "Roll No   : " <<rollNo << endl;

void outData(Student &st){
	ofstream out;
	out.open("obj.txt",ios::app | ios::binary);
	out.write((char *)&st,sizeof(st));

void inData(Student st){
	int count =0;
	ifstream in;
	while(in.eof()!= 1){
		in.read((char *)&st,sizeof(st));


int main()
	Student st;
	return 0;

This: while(in.eof()!= 1)
is probably why it is always shows the last object read in twice. You shouldn't use the return value of eof() to control performance of a loop body for that very reason. Lot's of folks have bookmarked a reference to a technical explanation for why that's so, but I've never really understood it all that well, so I won't try to explain it. I just know this type of problem can develop when you use that type of approach. To try to fix it, try this:

while(in.read((char *)&st,sizeof(st)))
Damned eof() !!
thank u so much for the help, as tomorow is my exam, and i was never interested in filing , but today i have to learn. after your help i will definatly get 10 marks from flinig Q .... ;)

Well how have you written the records in the file from which you are taking the input ?
Extras :
>Try not using .eof() function its not good to use it like this several times discussed already in this forum.
>And within the read looping you can always include a counter right to know how much you have read.

This question has already been answered. Start a new discussion instead.