简体   繁体   English

unix中read和pread有什么区别?

[英]What is the difference between read and pread in unix?

What is the difference between the functions read() and pread() in unix? unix中的函数read()pread()什么区别?
When choosing between them, what points should I take into consideration? 在他们之间做出选择时,我应该考虑哪些方面?

I googled for the difference between them but without results. 我用谷歌搜索他们之间的差异,但没有结果。

Pread() works just like read() but reads from the specified position in the file without modifying the file pointer. Pread()的工作方式与read()类似,但是从文件中的指定位置读取而不修改文件指针。

You would use it when you need to repeatedly read data at fixed offset, for example a database index that points to individual records in file, to save on seek() calls. 当您需要以固定偏移量重复读取数据时,可以使用它,例如指向文件中各个记录的数据库索引,以保存在seek()调用上。

Basically use read() if your data is sequential or pread() if you know, or can calculate offset at which to read. 如果您的数据是连续的,则基本上使用read(),如果您知道,则使用pread() ,或者可以计算读取的偏移量。

From this link , 从这个链接

The atomicity of pread enables processes or threads that share file descriptors to read from a shared file at a particular offset without using a locking mechanism that would be necessary to achieve the same result in separate lseek and read system calls. pread的原子性使共享文件描述符的进程或线程能够从特定偏移量的共享文件中读取,而不使用在单独的lseek和read系统调用中实现相同结果所必需的锁定机制。 Atomicity is required as the file pointer is shared and one thread might move the pointer using lseek after another process completes an lseek but prior to the read. 由于文件指针是共享的,因此需要原子性,并且在另一个进程完成lseek之后但在读取之前,一个线程可能使用lseek移动指针。

Google gave me man pread . 谷歌给了我man pread

If you read() twice, you get two different results, which shows that read() advances in the file. 如果您read()两次,则会得到两个不同的结果,这表明read()在文件中前进。

If you pread( ) twice, you get the same result, which shows that pread() stays at the same point in the file. 如果你pread( )两次,你得到相同的结果,这表明pread()停留在文件中的同一点。

read() starts reading the requested number of bytes from the current file offset whereas with pread(), you can specify the offset. read()从当前文件偏移量开始读取请求的字节数,而使用pread(),可以指定偏移量。 This is useful in situations where one set of functions is reading through a file sequentially using the file pointer while another set is accessing specific data at the same time. 这在一组函数使用文件指针顺序读取文件而另一组函数同时访问特定数据的情况下非常有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM