The Wayback Machine - https://web.archive.org/web/20241109204602/https://www.geeksforgeeks.org/implement-your-own-tail-read-last-n-lines-of-a-huge-file/
Open In App

Implement your own tail (Read last n lines of a huge file)

Last Updated : 29 May, 2017
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a huge file having dynamic data, write a program to read last n lines from the file at any point without reading the entire file. The problem is similar to tail command in linux which displays the last few lines of a file. It is mostly used for viewing log file updates as these updates are appended to the log files.

Source : Microsoft Interview

We strongly recommend you to minimize your browser and try this yourself first.

The problem mainly focuses on below things –

1. The program should not read entire file.
2. The program should handle incoming dynamic data and returns last n lines at any point.
3. The program should not close input stream before reading last n lines.

Below is its C++ implementation




// C++ program to implement your own tail
#include <bits/stdc++.h>
using namespace std;
  
#define SIZE 100
  
// Utility function to sleep for n seconds
void sleep(unsigned int n)
{
    clock_t goal = n * 1000 + clock();
    while (goal > clock());
}
  
// function to read last n lines from the file
// at any point without reading the entire file
void tail(FILE* in, int n)
{
    int count = 0;  // To count '\n' characters
  
    // unsigned long long pos (stores upto 2^64 – 1
    // chars) assuming that long long int takes 8 
    // bytes
    unsigned long long pos;
    char str[2*SIZE];
  
    // Go to End of file
    if (fseek(in, 0, SEEK_END))
        perror("fseek() failed");
    else
    {
        // pos will contain no. of chars in
        // input file.
        pos = ftell(in);
  
        // search for '\n' characters
        while (pos)
        {
            // Move 'pos' away from end of file.
            if (!fseek(in, --pos, SEEK_SET))
            {
                if (fgetc(in) == '\n')
  
                    // stop reading when n newlines
                    // is found
                    if (count++ == n)
                        break;
            }
            else
                perror("fseek() failed");
        }
  
        // print last n lines
        printf("Printing last %d lines -\n", n);
        while (fgets(str, sizeof(str), in))
            printf("%s", str);
    }
    printf("\n\n");
}
  
// Creates a file and prints and calls tail() for 
// 10 different values of n (from 1 to 10)
int main()
{
    FILE* fp;
    char buffer[SIZE];
    // Open file in binary mode
    // wb+ mode for reading and writing simultaneously
    fp = fopen("input.txt", "wb+");
    if (fp == NULL)
    {
        printf("Error while opening file");
        exit(EXIT_FAILURE);
    }
    srand(time(NULL));
  
    // Dynamically add lines to input file
    // and call tail() each time
    for (int index = 1; index <= 10; index++)
    {
        /* generate random logs to print in input file*/
        for (int i = 0; i < SIZE - 1; i++)
            buffer[i] = rand() % 26 + 65; // A-Z
        buffer[SIZE] = '\0';
  
        /* code to print timestamp in logs */
        // get current calendar time
        time_t ltime = time(NULL);
  
        // asctime() returns a pointer to a string
        // which represents the day and time
        char* date = asctime(localtime(<ime;));
  
        // replace the '\n' character in the date string
        // with '\0' to print on the same line.
        date[strlen(date)-1] = '\0';
  
        /* Note in text mode '\n' appends two characters,
        so we have opened file in binary mode */
        fprintf(fp, "\nLine #%d [%s] - %s", index,
                                    date, buffer);
  
        // flush the input stream before calling tail
        fflush(fp);
  
        // read last index lines from the file
        tail(fp, index);
  
        // sleep for 3 seconds
        // note difference in timestamps in logs
        sleep(3);
    }
  
    /* close the file before ending program */
    fclose(fp);
  
    return 0;
}


Some points to Note –
1. This code won’t work on online compiler as it requires file creation permissions. When run local machine, it produces sample input file “input.txt” and dynamically write data to it 10 times and calls tail() function every time.

2. We should avoid using fseek() and ftell() for huge files(in GBs) as they operate on file positions of type long int. Use _fseeki64(), _ftelli64() instead.

3. unsigned long has max allowed value of 232 – 1 (Assuming that unsigned long takes 4 bytes). It can be used for files size of less than 4 GB file.

4. unsigned long long has max allowed value of 264 – 1 (Assuming that unsigned long long takes 8 bytes). It can be used for files size over 4 GB.



Similar Reads

Implement Your Own sizeof
Here is an implementation. #include<stdio.h> #define my_sizeof(type) (char *)(&type+1)-(char*)(&type) int main() { double x; printf("%ld", my_sizeof(x)); getchar(); return 0; } Type is like a local variable to the macro. &type gives the address of the variable (double x) declared in the program and incrementing it with 1
2 min read
Implement Your Own itoa()
The itoa function converts an integer into a null-terminated string. It can convert negative numbers too. It is a standard library function that is defined inside stdlib.h header file. Syntax of itoa in Cchar* itoa(int num, char* buffer, int base);In this article, we create a C Program to implement a custom function that will be able to convert the
4 min read
Near, Far and Huge Pointers in C
In older times, the intel processors had 16-bit registers but the address bus was 20-bits wide. Due to this, the registers were not able to hold the entire address at once. As a solution, the memory was divided into segments of 64 kB size, and the near pointers, far pointers, and huge pointers were used in C to store the addresses. There are old co
4 min read
Reading Lines by Lines From a File to a Vector in C++ STL
Prerequisites: STL in C++Vector in C++File handling in C++ The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms, and iterators. Vector in C++ STL Vectors are the same as dynamic arrays with
2 min read
How to write your own header file in C?
As we all know that files with .h extension are called header files in C. These header files generally contain function declarations which we can be used in our main C program, like for e.g. there is need to include stdio.h in our C program to use function printf() in the program. So the question arises, is it possible to create your own header fil
4 min read
How to implement our own Vector Class in C++?
The given task is to implement a class in C++ which behaves just like the Vector class.Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can b
5 min read
How to Write Your Own printf() in C?
In this article, we will learn how to implement your own custom printf() function in C language. The printf() function is present in <stdio.h> header and uses a const char* and variable length arguments as its parameters. Hence we would be using <stdarg.h> header file which provides operations available on variable arguments passed to a
4 min read
How to Create Your Own scanf() in C?
The scanf() function is used to take input from the console. It is defined in <stdio.h> header file and takes const char* and variable argument list as parameters. In this article, we will learn how to implement your own custom scanf() function in C language. For this, we need to have a firm grasp of the following concepts: Prerequisites: Var
3 min read
Write your own strlen() for a long string padded with '\0's
Given a big character array that represents a string such that all trailing non-string characters are filled with '\0' at the end, i.e, all leading characters are string characters, all trailing are '\0' and no garbage characters. Write an efficient function to find length of such a string. Examples: Input: str[] = {'g', 'e', 'e', 'k', '\0', '\0',
3 min read
Write your own memcpy() and memmove()
The memcpy function is used to copy a block of data from a source address to a destination address. Below is its prototype. void * memcpy(void * destination, const void * source, size_t num);The idea is to simply typecast given addresses to char *(char takes 1 byte). Then one by one copy data from source to destination. Below is implementation of t
4 min read
Making your own Linux Shell in C
To know more about what a shell is, click here. We all use the built in terminal window in Linux distributions like Ubuntu, Fedora, etc. But how do they actually work? In this article, We are going to handle some under the hood features and algorithms what actually work inside a shell. All Linux operating systems have a terminal window to write in
7 min read
Program to print last 10 lines
Given some text lines in one string, each line is separated by ‘\n’ character. Print the last ten lines. If number of lines is less than 10, then print all lines. Source: Microsoft Interview | Set 10 Following are the steps 1) Find the last occurrence of DELIM or '\n' 2) Initialize target position as last occurrence of '\n' and count as 0 , and do
4 min read
Tail Call Optimisation in C
In C programming, Tail Call Optimization (TCO) is a technique that eliminates the need for an additional stack frame to store the data of another function by reusing the current function's stack frame. This optimization technique is only possible for tail function calls. What is Tail Call?The tail call is the type of function call where another fun
4 min read
C Program to count number of lines in a file
C/C++ Code /* C Program to count the Number of Lines in a Text File */ #include <stdio.h> #define MAX_FILE_NAME 100 int main() { FILE *fp; int count = 0; // Line counter (result) char filename[MAX_FILE_NAME]; char c; // To store a character read from file // Get file name from user. The file should be // either in current folder or complete p
1 min read
How to Read and Parse Json File with RapidJson?
RapidJSON is a high-performance JSON library for C++. It provides a fast and easy-to-use interface for parsing and generating JSON. It is small but complete. It supports both SAX and DOM style API. Also, it is self-contained and header-only. It does not depend on external libraries such as BOOST. It even does not depend on STL. Here is an example o
5 min read
RapidJSON - File Read/Write in C++
RapidJSON is a C++ library for parsing and generating JSON (JavaScript Object Notation) data. It is designed for high performance and can handle very large JSON documents. RapidJSON supports both reading and writing JSON data, as well as validation and manipulation of JSON objects. It also includes support for parsing and generating JSON in a strea
6 min read
cJSON - JSON File Write/Read/Modify in C
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read and write for humans and machines alike. JSON is widely used for data exchange between applications and web services. In this article, we will discuss how to read and write JSON data in the C programming language. JSON in C JSON in C can be handled using
6 min read
lseek() in C/C++ to read the alternate nth byte and write it in another file
From a given file (e.g. input.txt) read the alternate nth byte and write it on another file with the help of “lseek”. lseek (C System Call): lseek is a system call that is used to change the location of the read/write pointer of a file descriptor. The location can be set either in absolute or relative terms. Function Definition off_t lseek(int fild
2 min read
Read/Write Class Objects from/to File in C++
Given a file "Input.txt" in which every line has values same as instance variables of a class. Read the values into the class's object and do necessary operations.Theory : The data transfer is usually done using '>>' and <<' operators. But if you have a class with 4 data members and want to write all 4 data members from its object direc
3 min read
Read/Write Structure From/to a File in C
For writing in the file, it is easy to write string or int to file using fprintf and putc, but you might have faced difficulty when writing contents of the struct. fwrite and fread make tasks easier when you want to write and read blocks of data. Writing Structure to a File using fwriteWe can use fwrite() function to easily write a structure in a f
3 min read
When should we write our own assignment operator in C++?
The answer is same as Copy Constructor. If a class doesn't contain pointers, then there is no need to write assignment operator and copy constructor. The compiler creates a default copy constructor and assignment operators for every class. The compiler created copy constructor and assignment operator may not be sufficient when we have pointers or a
3 min read
Implementing own Hash Table with Open Addressing Linear Probing
Prerequisite - Hashing Introduction, Implementing our Own Hash Table with Separate Chaining in JavaIn Open Addressing, all elements are stored in the hash table itself. So at any point, size of table must be greater than or equal to total number of keys (Note that we can increase table size by copying old data if needed). Insert(k) - Keep probing u
13 min read
When Should We Write Our Own Copy Constructor in C++?
A copy constructor is a member function that initializes an object using another object of the same class. (See this article for reference). When should we write our own copy constructor?C++ compiler provides a default copy constructor (and assignment operator) with class. When we don't provide an implementation of the copy constructor (and assignm
2 min read
How to Write Our Own STL Container?
The Standard Template Library (STL) in C++ provides us with various data structures and algorithms. We have STL containers like vector, list, map, and set that we commonly use to store and manipulate data efficiently. However, there are situations where the existing STL containers may not meet our specific requirements, so we may want to create our
7 min read
Does C++ compiler create default constructor when we write our own?
No, the C++ compiler doesn't create a default constructor when we define any type of constructor manually in the class. ExplanationThe default constructor is used to create an object's instance without any arguments. In C++, the compiler implicitly creates a default constructor for every class which doesn't have user defined constructor so that at
2 min read
Difference Between C++ Text File and Binary File
A text file is the one in which data is stored in the form of ASCII characters and is normally used for storing a stream of characters. Text files are organized around lines, each of which ends with a newline character ('\n'). The source code files are themselves text files. A binary file is the one in which data is stored in the file in the same w
4 min read
C program to copy contents of one file to another file
[GFGTABS] C #include <stdio.h> #include <stdlib.h> // For exit() int main() { FILE *fptr1, *fptr2; char filename[100]; int c; printf("Enter the filename to open for reading: "); scanf("%s", filename); // Open one file for reading fptr1 = fopen(filename, "r"); if (fptr1 == NULL) { printf("Cannot open fi
1 min read
Lex program to count the number of lines, spaces and tabs
Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.Let's the how to count the number of lines, spaces and tabs using Lex. Example: Input: Geeks for Geeks gfg gf
1 min read
Printing Output in Multiple Lines in C++
This article focuses on discussing how to use cout for multi-line printing. This can be easily done using any of these two methods: Using endl.Using \n. Let's discuss each of these methods in detail. Using endl The endl statement can be used to print the multi-line string in a single cout statement. Below is the C++ program to show the same: C/C++
2 min read
How to write long strings in Multi-lines C/C++?
Image a situation where we want to use or print a long long string in C or C++, how to do this? In C/C++, we can break a string at any point in the middle using two double quotes in the middle. Below is a simple example to demonstrate the same. C/C++ Code #include<stdio.h> int main() { // We can put two double quotes anywhere in a string char
2 min read
Practice Tags :
three90RightbarBannerImg