In a language of your choice write a function that is equivalent to calling the command tail -n, N for an arbitrary integer N, only using the standard library.
I used C++ for this question and it was really messy. I would very much like to know if there is an elegant way to do this.
Here is my solution(I assumed the value of n as 10):
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class File
{
private: string fileName;
ifstream file;
public: File(string fname)
{
fileName = fname;
}
void openFile();
void closeFile();
int countlines();
void printlines();
};
void File::openFile()
{
file.open(fileName.c_str());
if (!file)
{
cout << "File not opening!" << endl;
}
}
void File::closeFile()
{
file.close();
}
int File::countlines()
{
int lineCount = 0;
string str;
if (file)
{
while (getline(file, str))
{
lineCount += 1;
}
}
return lineCount;
}
void File::printlines()
{
int lineCount = 0;
string line;
if (file)
{
lineCount = countlines();
file.clear();
file.seekg(ios::beg);
if (lineCount <= 10)
{
while (getline(file, line))
{
cout << line << endl;
}
}
else
{
int position = lineCount - 10;
while (position--)
{
getline(file, line);
}
while (getline(file, line))
{
cout << line << endl;
}
}
}
}
int main()
{
cout << "Enter your file name: ";
cin >> fileName;
File file(fileName);
file.openFile();
file.printlines();
file.closeFile();
return 0;
}