Home C C++ Java Python Perl PHP SQL JavaScript Linux Selenium QT Online Test

Home » Linux » tail command

Example of tail command in Linux

1. Tail command is used to display the content of any file.
2. By default the last 10 lines are selected.
3. We can pass number of lines to be selected by using -n.
4. We can terminate the tail command by press Ctrl+C
5. Command 'tail -n 5 filename' will show the last 5 lines of any file.
6. Command 'tail +5 filename' will show all lines starting from line 5 till end of the file.
7. Command 'tail -c 5 filename' will show last 5 bytes(characters) starting from the end.
8. Command 'tail -v filename' also show the filename in output with default count of line as 10.
9. Command 'tail -n 5 filename | sort' sort the lines alphabetically.
10.Command 'tail -f filename' is useful in seeing any file which is being updated continously.

Let's make a small application which will udpate a log file continously, and we will try to check the logs using 'tail -f log.txt' command -

#include<iostream>
#include<fstream>
#include<signal.h>
using namespace std;
    
    class logger
{
private: ofstream out;
public:
        logger(){
                cout<<"in constructor";
                out.open("logger.txt", ofstream::app);
    
        ~logger(){
                cout<<"in destructors";
                out<<"in destructors";
                out.close();
        }
        void log(string str){
                out<<str<<"\n";
        }
        void flush(){
                out.flush();
        }
}obj;

void signal_callback_handler(int signum) {
   cout << "Caught signal " << signum << endl;
   obj.~logger();
   // Terminate program
   exit(signum);
}

int main()
{       signal(SIGINT, signal_callback_handler);
        while(1){
                obj.log("Hello");
                cout<<"\n writting into file";
                obj.flush();
                sleep(1);
        }       return 0;
}



Video with tail command exaples