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();		
	}

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{
private:
	char name[30];
	int id;
	int rollNo;

public:
	Student(){}
	Student(char *n,int i, int r){
		strcpy_s(name,n);
		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));
	out.close();
}

void inData(Student st){
	int count =0;
	ifstream in;
	in.open("obj.txt",ios::in|ios::binary);
	while(in.eof()!= 1){
		in.read((char *)&st,sizeof(st));
		st.showData();		
	}

	in.close();

}
int main()
{
		
	Student st;
	inData(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)))
{		
   st.showData();			
}
commented: 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 .... ;) +1
commented: Damned eof() !! +10

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.

Find the length of file. Divide the length of file by size of an object.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.