“fseek”、“lseek”、“seekg”、“seekp”有什么区别?

时间:2022-11-07 07:32:55

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.

一个采访者问我如何实现tail(是的,linux shell中的一个)。我的回答是,首先查找文件的末尾,然后逐个读字符,如果遇到一个\n,意味着一行写下来,等等。我想我的答案是对的。

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?).

然后我发现了这个问题,我应该用哪个查找来实现tail?我认为我可以简单地使用seekg (c++的东西?),但是我被告知我应该使用lseek (linux系统调用?)

So including fseek (ANSI C thing?), which one should I use to implement tail? And is there any big difference between them?

包括fseek (ANSI C),我应该用哪个实现tail?它们之间有什么大的区别吗?

1 个解决方案

#1


15  

Use seekg when using the C++ IOstreams library. seekp is no use here, since it sets the put pointer.

使用c++ IOstreams库时使用seekg。这里没用seekp,因为它设置了put指针。

Use fseek when using the C stdio library. Use lseek when using low-level POSIX file descriptor I/O.

使用C stdio库时使用fseek。使用低级POSIX文件描述符I/O时使用lseek。

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.

各种查找函数之间的区别仅仅是它们运行的文件/流对象。在Linux上,seekg和fseek可能是用lseek来实现的。

#1


15  

Use seekg when using the C++ IOstreams library. seekp is no use here, since it sets the put pointer.

使用c++ IOstreams库时使用seekg。这里没用seekp,因为它设置了put指针。

Use fseek when using the C stdio library. Use lseek when using low-level POSIX file descriptor I/O.

使用C stdio库时使用fseek。使用低级POSIX文件描述符I/O时使用lseek。

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.

各种查找函数之间的区别仅仅是它们运行的文件/流对象。在Linux上,seekg和fseek可能是用lseek来实现的。