I wrote a program that should print the last 5 lines of a file, but the teacher created a file with a line of 4 GB, and the program broke. How to rewrite a program so that it can work with very large files
a possible solution is to read the file character by character, but I don’t know how to do it
here is the c ++ program code
#include <iostream>
#include <fstream>
#include <string>
using std::ifstream;
using std::cout;
using std::string;
using std::getline;
int main(int argc, char * argv[], char * env[]) {
setlocale(LC_ALL, "");
int i;
string line;
if (argc == 3) {
string filename = argv[1];
ifstream myfile(filename);
string n = argv[2];
int nn = atoi(n.c_str());
string line, buffer[nn];
const size_t size = sizeof buffer / sizeof * buffer;
size_t i = 0;
while (getline(myfile, line)) {
buffer[i] = line;
if (++i >= size) {
i = 0;
}
}
for (size_t j = 0; j < size; ++j) {
cout << buffer[i] << "\n";
if (++i >= size) {
i = 0;
}
}
//return 0;
}
}