카테고리 없음

Exercise 12.3: Advanced File Operations

07514673 2021. 12. 20. 14:49

Exercise 12.3: Advanced File Operations

Here is the problem specification:

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.

The content of Payroll.txt

1#23400
4#17000
5#21000
6#12600
9#26700
10#18900
11#18500
13#12000
15#49000
16#56500
20#65000
21#65500
22#78200
23#71000
24#71100
25#72000
30#83000
31#84000
32#90000

 

Sample Run

Enter the file name: Payroll.txt
16#56500
20#65000
21#65500
22#78200
23#71000
24#71100
25#72000
30#83000
31#84000
32#90000

#include <iostream>
#include <fstream>
#include <vector>
#include<string>
using namespace std;
void createFile(string fileName) {
    fstream file;
    file.open(fileName, ios::out);
    file << "1#23400\n";
    file << "4#17000\n";
    file << "5#21000\n";
    file << "6#12600\n";
    file << "9#26700\n";
    file << "10#18900\n";
    file << "11#18500\n";
    file << "13#12000\n";
    file << "15#49000\n";
    file << "16#56500\n";
    file << "20#65000\n";
    file << "21#65500\n";
    file << "22#78200\n";
    file << "23#71000\n";
    file << "24#71100\n";
    file << "25#72000\n";
    file << "30#83000\n";
    file << "31#84000\n";
    file << "32#90000\n";
    
    file.close();
}
int main()
{
    fstream inputFile;
    string fileName, temporary;
    vector<string> fileLines;
    cout << "Enter the file name: ";
    cin >> fileName;
    inputFile.open(fileName, ios::out | ios::in);
    //createFile(fileName);
    
    while (!inputFile.eof()) {
        getline(inputFile, temporary,'\n');
        fileLines.push_back(temporary);
    }
    for (int i = fileLines.size() - 11; i < fileLines.size(); i++) {
        cout << fileLines.at(i) << endl;
    }
    inputFile.close();
    return 0;
}