Reading part of a file

Hi, I've been wondering if there's a way to show only some part of a file when it reaches a limit, i.e I have this code that shows the latest orders of a restaurant, so every time that an order is made the program saves it to a file.
But I don't know if is possible to show only the last 10 or 15 orders

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
int Day, Month, Menu;
double Price;

Lec.open("Orders.txt", ios::in);
if(Lec.is_open()){

    cout << "Latest orders" << endl << endl;

    Lec>>Day;

    while(!Lec.eof()){
        Lec>>Month;
        Lec>>opc_menu;
        Lec>>Price;
        cout << "Day------------------:" << Day << endl;
        cout << "Month----------------:" << Month << endl;
        cout << "Order----------------:" << Menu << endl;
        cout << "Bill-----------------:" << Price << endl;
        cout << "----------------------" << endl;
        Lec>>Day;
    }
    Lec.close();
}else
cout << "The file couldn't be open or it doesn't exist" << endl;
system ("pause");
Last edited on
1) If the latest orders are at the start of the file, then it's easy - just maintain a count of the number of orders you've printed, and stop printing when you've done the first 15.

2) Otherwise, you'll probably need to read the whole file into memory first, identify the latest 15 orders, and then print those 15 out.
Create a struct to contain all your data.

Each order you read from the file (into a struct), you do
https://www.cplusplus.com/reference/deque/deque/push_back/

While the size is >= 15,
https://www.cplusplus.com/reference/deque/deque/size/
do this
https://www.cplusplus.com/reference/deque/deque/pop_front/
check out binary mode
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
struct order{
	int day, month;
	int order;
	double price;
};

ifstream database("orders.dat", ios::binary | ios::ate); //binary mode, start at the end

int n=15;
database.seekg(-n*sizeof(order), ios::cur); //go back 15 positions
for(int K=0; K<n; ++K){
	order the_order;
	database.read((char*) &the_order, sizeof(the_order)); //read one order
	cout << "day: " << the_order.day << '\n';
	//...
}

of course, the creation of the file ought to be in that mode too.
Topic archived. No new replies allowed.