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

前端 未结 3 1263
温柔的废话
温柔的废话 2021-02-05 05:24

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

3条回答
  •  北荒
    北荒 (楼主)
    2021-02-05 05:40

    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.

提交回复
热议问题