I was asked by an interviewer that how would I implement tail
(yes, the one in linux shell). My answer was, first seek to the end of the file, then read characters one-by-one forward, if encounters a \n
, means one line is down, blah blah blah. I assume my answer is correct.
Then I found this problem, which seek should I use to implement tail
? I thought I can simply use seekg
(C++ thing?), but I was told that I should use lseek
(linux system call?).
So including fseek
(ANSI C thing?), which one should I use to implement tail
? And is there any big difference between them?
seekg moves the file input pointer(position of reading frm file) while seekp moves file output pointer( position f writing to file).
seekg() and seekp() both are functions of File Handling in C++ and they are very important and useful feature of File Handling in C++. In File Handling of C++, we have two pointers one is get pointer and second is put pointer.
seekg() is a function in the iostream library that allows you to seek an arbitrary position in a file. It is included in the <fstream> header file and is defined for istream class. It is used in file handling to sets the position of the next character to be extracted from the input stream from a given file.
The tellp() function is used with output streams, and returns the current “put” position of the pointer in the stream. It has no parameters and return a value of the member type pos_type, which is an integer data type representing the current position of the put stream pointer.
Use seekg
when using the C++ IOstreams library. seekp
is no use here, since it sets the put pointer.
Use fseek
when using the C stdio library. Use lseek
when using low-level POSIX file descriptor I/O.
The difference between the various seek functions is just the kind of file/stream objects on which they operate. On Linux, seekg
and fseek
are probably implemented in terms of lseek
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With