What are the advantages of pwrite and pread over fwrite and fread?

二次信任 提交于 2020-06-09 11:59:06

问题


Hey please don't mind if I am asking trivial question, but, please can somebody help me with this..


回答1:


It's useful when you do a lot of random read/write operations. There is even an option for SQLite3 that replaces seek() + read() and seek()+ write() with pread()/pwrite().

The advantage: seek()+ read() and seek() + write() both are the pairs of system calls while pread() and pwrite() are single system calls. It's usually an universal truth that the less system calls program issues the more efficient it is.




回答2:


There are two parts:

  1. Difference between pread/pwrite and read/write:

    They are both at the same level, namely system calls. There are two differences:

    1. The "p" variants take offset to read from, so they are independent of the current file pointer. That makes it easier to read/write from multiple threads concurrently.
    2. The "p" variants only work on seekable files (i.e. real files, not pipes, sockets or devices).
  2. Difference between read/pread/write/pwrite and fread/fwrite:

    The "f" variants are standard runtime wrappers of the former (using the basic variants). They support in-process buffering. That can significantly improve performance for simple code, but it makes use of other features of the system-call level impractical.

Only use the "p" variants if you have good use for reading at random offsets (avoiding seeks and allowing concurrent access via one file handle), which often the case with some kind of database files (record-oriented with records at known offsets) and rarely in other applications.




回答3:


Current file position doesn't change after a call to pread/pwrite.

Also because you don't need to call lseek to change the current file position pread/pwrite avoid potential race conditions when multiple threads are involved.



来源:https://stackoverflow.com/questions/7592822/what-are-the-advantages-of-pwrite-and-pread-over-fwrite-and-fread

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!