C语言 在偏移量处从文件描述符读取/写入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19780919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:53:10  来源:igfitidea点击:

Read/write from file descriptor at offset

cfile-descriptor

提问by zaloo

I've been using the read(2)and write(2)functions to read and write to a file given a file descriptor.

我一直在使用read(2)write(2)函数来读取和写入给定文件描述符的文件。

Is there any function like this that allows you to put an offset into the file for read/write?

是否有任何这样的功能允许您将偏移量放入文件中以进行读/写?

采纳答案by paddy

Yes, you're looking for lseek.

是的,您正在寻找lseek.

http://linux.die.net/man/2/lseek

http://linux.die.net/man/2/lseek

回答by Sergey Podobry

There are pread/pwritefunctions that accept file offset:

有接受文件偏移量的pread/pwrite函数:

ssize_t pread(int fd, void *buf, size_t count, off_t offset);
ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset);

回答by Darren Stone

Yes. You use the lseekfunction in the same library.

是的。您lseek同一个库中使用该函数。

You can then seek to any offset relative to the start or end of file, or relative to the current location.

然后,您可以查找相对于文件开头或结尾或相对于当前位置的任何偏移量。

Don't get overwhelmed by that library page. Here are some simple usage examples and probably all most people will ever need:

不要被那个图书馆页面淹没。以下是一些简单的使用示例,可​​能大多数人都需要:

lseek(fd, 0, SEEK_SET);   /* seek to start of file */
lseek(fd, 100, SEEK_SET); /* seek to offset 100 from the start */
lseek(fd, 0, SEEK_END);   /* seek to end of file (i.e. immediately after the last byte) */
lseek(fd, -1, SEEK_END);  /* seek to the last byte of the file */
lseek(fd, -10, SEEK_CUR); /* seek 10 bytes back from your current position in the file */
lseek(fd, 10, SEEK_CUR);  /* seek 10 bytes ahead of your current position in the file */

Good luck!

祝你好运!

回答by Potatoswatter

lseek()and ye shall? receive.

lseek()你会吗?收到。

回答by Yu Hao

Yes, you can use lseek():

是的,您可以使用lseek()

off_t lseek(int fd, off_t offset, int whence);

The lseek()function repositions the offset of the open file associated with the file descriptor fdto the argument offset according to the directive whenceas follows:

SEEK_SET

The offset is set to offset bytes.

SEEK_CUR

The offset is set to its current location plus offset bytes.

SEEK_END

The offset is set to the size of the file plus offset bytes.

lseek()函数根据指令将与文件描述符关联的打开文件的偏移量重新定位fd到参数offset whence,如下所示:

SEEK_SET

偏移量设置为偏移字节。

SEEK_CUR

偏移量设置为其当前位置加上偏移量字节。

SEEK_END

偏移量设置为文件大小加上偏移字节数。