Objective:
Write a program that asks the user for the name of a file. The program should display
the last 10 lines of the file on the screen (the “tail” of the file). If the file has fewer than
10 lines, the entire file should be displayed, with a message indicating the entire file
has been displayed.
NOTE:
Using an editor, you should create a simple text file that can be used to test this
program.
#include <iostream>
#include <fstream>
using namespace std;
void readFile(const string& fileName);
void displayTail(ifstream &);
void test();
int main() {
string fileName;
cout << "Please enter the name of the file you wish to open:\n";
cin >> fileName;
readFile(fileName);
// comment all lines in main func and uncomment next line to run test
// test();
return 0;
}
void readFile(const string& fileName) {
ifstream inputFile;
inputFile.open(fileName, ios::binary);
displayTail(inputFile);
inputFile.close();
}
void displayTail(ifstream &inputFile) {
inputFile.seekg(0L, ios::beg);
long pos = inputFile.tellg();
char ch;
inputFile.seekg(0L, ios::end);
inputFile.clear();
int counter = 0;
while (counter < 10 && pos != inputFile.tellg()) {
inputFile.seekg(-1L, ios::cur);
if (inputFile.peek() == '\n') {
counter++;
}
}
if (counter < 9) {
cout << "There are less than 10 lines inside this file\n";
cout << "Displaying entire file\n";
}
while (!inputFile.eof()) {
cout << ch;
inputFile.get(ch);
}
}
void test() {
string testFileName = "test.txt";
ofstream testFile (testFileName);
if (testFile.is_open())
{
testFile << "This is a line1\n";
testFile << "This is a line2\n";
testFile << "This is a line3\n";
testFile << "This is a line4\n";
testFile << "This is a line5\n";
testFile << "This is a line6\n";
testFile << "This is a line7\n";
testFile << "This is a line8\n";
testFile << "This is a line9\n";
testFile << "This is a line10\n";
testFile << "This is a line11\n";
testFile << "This is a line12";
testFile.close();
readFile(testFileName);
}
else cout << "Unable to open file";
}
Comments
Leave a comment