I'm trying to write a program, when the program is performing an operation (Example: search, update, or add), it should be direct access. The program should not read all the records sequentially to reach a record.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct Student{
int Id;
int Money;
int Age;
char name[15];
};
void main(){
Student buffer;
ofstream BinaryFile("student", ios::binary);
ifstream WorkerText("worker.txt");
//-------------------------------------------------------------------------------------------------------------
while( WorkerText.good() ){
WorkerText>> buffer.Age >> buffer.name >> buffer.name >> buffer.name;
BinaryFile.write( (char *) &buffer, sizeof(Student) );
}
BinaryFile.close();
//-------------------------------------------------------------------------------------------------------------
ifstream ReadBinary( "student", ios::binary | ios::out );
while( BinaryFile.good() ){
ReadBinary.read((char*)&buffer,sizeof(Student));
cout<<buffer.Age;
}
//-------------------------------------------------------------------------------------------------------------
system("pause");
}
I stucked here I could not read sequentially how can I solve this
There are three options to avoid sequential reads:
You can skip sequential read only if the file contains structures of the same size, or uses some index table.
For the case of structures of same size:
The functions above assume you are writing data as follows:
You are using "out" mode when you open the student file for input:
Try this:
The
ifstream
constructor already opens the file in input mode (ios::in
).When we want to do search (and subsequent update) but store records in flat file sequentially, you need to have external index to help you get direct access to desired record ! Say in this case you want to search student by name and then update record, you can do some thing like this:
These all assume that your struct is fixed size one (which it is in your example).