I am trying to enter data through classes in a binary file using file handling. But what I am unable to do is to write data in a sorted manner. Like I can’t figure out how can I uniquely identify one of the records I had inserted in the past in that particular file. Why I am trying to do so? Because I want to be able to perform operations like deleting, modifying a particular record. I tried using static variable but I want to hold that value until I run the program the next time which is not possible with static. BTW this is the class.
class question
{
private:
char question[500];
char option1[25],option2[25],option3[25],option4[25];
int answernumber;
public:
int qno;
void createquestion(); // Just to to accept data into
// question,options,answernumebr.
}
Now the only problem is assigning qno which is question number. I am planning to use it as my Primary key( wrong to use this word) . But I just can’t figure it out how to automatically assign it its corresponding values without user intervention? Any suggestions?
EDIT:- I also tried to do this—> I thought of reading the last record entered and then extract the corresponding question number. And then assign that number and add 1 to it…so old_qno+1=new_qno….. But unfortunately didn’t worked out too well. as All my questions were being assigned as question 1 only
You can use the size of the file you have written as way of counting of the number questions you have so far.
But you have to be careful with deletes, suppose you have questions 1, 2, 3, 4 in your file and then you delete question 3. Now your file has 1, 2, 4 and so the method above will say the next question is 4, but you already have a question 4. One way to deal with this is to do logical deletes. Instead of actually deleting a question from a file you leave it there but mark it in some way so you know it’s deleted. For instance you could set the question number to zero. So going back to the example above after you deleted question three you would have 1, 2, 0, 4. Now the file size method will correctly say the next question is 5.