Plz tell me how to sort the data in a binary FILE and write it back to a binary file..
Here is my coding !! Need HELP!
// rewobj.cpp
// person objects do disk I/O
#include <fstream> //for file streams
#include <iostream>
#include <string>
using namespace std;
////////////////////////////////////////////////////////////////
class Student //class of Students
{
protected:
char name[20];
char dept[10];
char year[5];
int roll_no;
void diskIn(int); //read from file
void diskOut(); //write to file
static int diskCount(); //return number of
void Add_student ();
void display ();
~Student ()
{}
// persons in file
};
//--------------------------------------------------------------
void Student::diskIn(int pn) //read person number pn
{ //from file
ifstream infile; //make stream
infile.open("STDFILE.DAT", ios::binary); //open it
infile.seekg( pn*sizeof(Student) ); //move file ptr
infile.read( (char*)this, sizeof(*this) ); //read one person
}
//--------------------------------------------------------------
void Student::diskOut() //write person to end of file
{
ofstream outfile; //make stream
//open it
outfile.open("STDFILE.DAT", ios::app | ios::binary);
outfile.write( (char*)this, sizeof(*this) ); //write to it
}
//--------------------------------------------------------------
int Student::diskCount() //return number of persons
{ //in file
ifstream infile;
infile.open("STDFILE.DAT", ios::binary);
infile.seekg(0, ios::end); //go to 0 bytes from end
//calculate number of persons
return (int)infile.tellg() / sizeof(Student);
}
switch (choice)
{
case 1: {
char ch;
do {
cout << "\n\nEnter Student data: ";
s.Add_student(); //get data
s.diskOut(); //write to disk
cout << "\n\nAnother (y/n) ? " ;
cin >> ch;
} while (ch=='y' );
break;
}
case 2: {
int n = Student::diskCount(); //how many persons in file?
cout << "\n\nTotal no of students = " << n << endl;
for (int i=0; i<n; i++)
{
cout << "\n\nStudent # " << i+1<<endl;
s.diskIn(i); //read person from disk
s.display(); //display person
cout << endl;
}
system ("pause");
This reminds me of: http://cplusplus.com/forum/lounge/31041/
Binary data is just an array of bytes. Order them the way you want using some algorithm.
As for a file, a file is literally nothing but binary data.
Figure out the size of the file, allocate an array the size of the data, read into the array, sort the array, write the array back into a file, and you're done.