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
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.
This article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- C Program to count number of lines in a file
- Read/Write structure to a file in C
- Read a record from a File in C++ using seekg() and tellg()
- Read/Write Class Objects from/to File in C++
- Lex program to take input from file and remove multiple spaces, lines and tabs
- lseek() in C/C++ to read the alternate nth byte and write it in another file
- C++ program to read file word by word
- What are near, far and huge pointers?
- C program to copy contents of one file to another file
- Program to print last 10 lines
- How to use getline() in C++ when there are blank lines in input?
- Print 2D matrix in different lines and without curly braces in C/C++?
- How to write long strings in Multi-lines C/C++?
- Lex program to count the number of lines, spaces and tabs
- How to Read and Print an Integer value in C++