Function pread for windows

By | February 13, 2012

The pread function is used to read N bytes from a stream/file from a given offset point. It is natively present on linux/unix but not on windows. However its easy to implement it on windows using the lseek and read functions. Here is an example

#include <io.h>
#include <stdio.h>

int pread(unsigned int fd, char *buf, size_t count, int offset)
	if (_lseek(fd, offset, SEEK_SET) != offset) {
		return -1;
	return read(fd, buf, count);


Last Updated On : 13th February 2012

3 thoughts on “Function pread for windows

  1. Elvis Stansvik

    Neither of these are proper pread(2) implementations, since they do not allow multiple threads to perform I/O on the same file descriptor without being affected by changes to the file offset by other threads, which is a guarantee that pread(2) gives.

    In both suggested implementations, if a thread A is running, another thread B could come in and do a seek on the same file descriptor in between the seek and read of thread A, thereby spoiling the read for thread A which would read from an unexpected offset.

    To implement pread(2) properly using basic lseek and read, you would need a locking primitive or a native function with support for atomic seek+read.

  2. tansy

    Your function should restore file pointer as pread() does not change it.
    it should look more like this:

    ssize_t pread_(int fd, void *buf, size_t count, off_t offset)
    ssize_t read_count;
    off_t cur_pos;

    cur_pos = lseek(fd, 0, SEEK_CUR);
    if (lseek(fd, offset, SEEK_SET) < 0)
    return -1;
    read_count = read(fd, buf, count);
    if (cur_pos != lseek(fd, current_offset, SEEK_SET))
    return -1;
    return read_count;
    #define pread pread_

Leave a Reply

Your email address will not be published. Required fields are marked *