Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print out the last 10 lines of a file

Tags:

c++

file

tail

cout

I want to have the option to print out the last 10 lines of a textfile . with this program I've been able to read the whole textfile, but I can't figure out how to manipulate the array in which the textfile is saved, any help?

// Textfile output
#include<fstream>
#include<iostream>
#include<iomanip>
using namespace std;

int main() {
    int i=1;
    char zeile[250], file[50];
    cout << "filename:" << flush;
    cin.get(file,50);                          ///// (1)
    ifstream eingabe(datei , ios::in);          /////(2)
    if (eingabe.good() ) {                       /////(3)           
       eingabe.seekg(0L,ios::end);               ////(4)
       cout << "file:"<< file << "\t"
            << eingabe.tellg() << " Bytes"       ////(5)
            << endl;
       for (int j=0; j<80;j++)
           cout << "_";
           cout << endl;
       eingabe.seekg(0L, ios::beg);              ////(6)
       while (!eingabe.eof() ){                  ///(7)
             eingabe.getline(zeile,250);         ///(8)
             cout << setw(2) << i++
                  << ":" << zeile << endl;
             }      
           }
    else
        cout <<"dateifehler oder Datei nicht gefunden!"
             << endl;
            
             return 0;
    }
like image 257
adler25 Avatar asked Feb 24 '23 09:02

adler25


2 Answers

Try this:

#include <list>
#include <string>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>

// A class that knows how to read a line using operator >>

struct Line
{
    std::string theLine;
    operator std::string const& () const { return theLine; }
    friend std::istream& operator>>(std::istream& stream, Line& l)
    {
        return std::getline(stream, l.theLine);
    }
};

// A circular buffer that only saves the last n lines.

class Buffer
{
    public:
        Buffer(size_t lc)
            : lineCount(lc)
        {}
        void push_back(std::string const& line)
        {
            buffer.insert(buffer.end(),line);
            if (buffer.size() > lineCount)
            {
                buffer.erase(buffer.begin());
            }
        }
        typedef std::list<std::string>      Cont;
        typedef Cont::const_iterator        const_iterator;
        typedef Cont::const_reference       const_reference;
        const_iterator begin()  const       { return buffer.begin(); }
        const_iterator end()    const       { return buffer.end();}

    private:
        size_t                      lineCount;
        std::list<std::string>      buffer;
};    

// Main

int main()
{
    std::ifstream   file("Plop");
    Buffer          buffer(10);

    // Copy the file into the special buffer.
    std::copy(std::istream_iterator<Line>(file), std::istream_iterator<Line>(),
            std::back_inserter(buffer));

    // Copy the buffer (which only has the last 10 lines)
    // to std::cout
    std::copy(buffer.begin(), buffer.end(),
            std::ostream_iterator<std::string>(std::cout, "\n"));
}
like image 109
Martin York Avatar answered Mar 08 '23 03:03

Martin York


Basically, you are not saving the file contents to any array. The following sample will give you a head start:

#include <iostream>
#include <vector>
#include <string>

int main ( int, char ** )
{
    // Ask user for path to file.
    std::string path;
    std::cout << "filename:";
    std::getline(std::cin, path);

    // Open selected file.      
    std::ifstream file(path.c_str());
    if ( !file.is_open() )
    {
        std::cerr << "Failed to open '" << path << "'." << std::endl;
        return EXIT_FAILURE;
    }

    // Read lines (note: stores all of it in memory, might not be your best option).
    std::vector<std::string> lines;
    for ( std::string line; std::getline(file,line); )
    {
        lines.push_back(line);
    }

    // Print out (up to) last ten lines.
    for ( std::size_t i = std::min(lines.size(), std::size_t(10)); i < lines.size(); ++i )
    {
        std::cout << lines[i] << std::endl;
    }
}

It would probably be wiser to avoid storing the whole file into memory, so you could re-write the last 2 segments this way:

// Read up to 10 lines, accumulating.
std::deque<std::string> lines;
for ( std::string line; lines.size() < 0 && getline(file,line); )
{
    lines.push_back(line);
}

// Read the rest of the file, adding one, dumping one.
for ( std::string line; getline(file,line); )
{
    lines.pop_front();
    lines.push_back(line);
}

// Print out whatever is left (up to 10 lines).
for ( std::size_t i = 0; i < lines.size(); ++i )
{
    std::cout << lines[i] << std::endl;
}
like image 39
André Caron Avatar answered Mar 08 '23 01:03

André Caron