Answer to Question #318647 in C++ for Rival

Question #318647

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.






1
Expert's answer
2022-03-26T14:01:53-0400
#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";
}


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS