Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the difference between `fseek`, `lseek`, `seekg`, `seekp`?

Tags:

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?

like image 459
Alcott Avatar asked Feb 19 '12 13:02

Alcott


People also ask

What is the difference between seekg and seekp?

seekg moves the file input pointer(position of reading frm file) while seekp moves file output pointer( position f writing to file).

What is the use of seekg () and seekp () functions?

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.

What is the use of seekg () function in C++?

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.

Which function is used to move the stream pointer for the purpose of writing data from stream?

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.


1 Answers

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.

like image 71
Fred Foo Avatar answered Sep 21 '22 18:09

Fred Foo