0
votes

I am looking at the man-page for read(int fd, void *buf, size_t count)

http://man7.org/linux/man-pages/man2/read.2.html

where I need some more explanation on the words "On files that support seeking, the read operation commences at the current file offset, and the file offset is incremented by the number of bytes read. "

1) If I want to read a file not from the beginning, say at offset 100 (bytes) to read 1 byte, is the offset 100 added to the fd, i.e, read(fd+100, buf, 1)? If not, how can I specify the offset in the code?

2) How do I know if "files support seeking"? I "opened" the FPGA as a spi device through spi bus, to get the fd. I am using read() to read registers of FPGA. In this case, is the file support seeking?

Thanks!

3

3 Answers

2
votes

You need to first move the file pointer (current file offset) to 100, via a read or seek call.

1
votes

Alternatively you might be interested in pread, depending on what you are doing. pread is equivalent of atomically (1) saving the current offset, (2) read the offset you want to read, and (3) restoring the original offset.

On your second question you will know if it isn't a seekable device because your call to lseek will fail. I don't know of any reliable way to know in advance.

0
votes

You use lseek to move the possition in the file -- so you would do something like

lseek(fd, 100, SEEK_SET);
read(fd, buffer, 1);

to read one byte at position 100.

However, while this is a valid example, I would advice not to read individual bytes in a file this way, as it is very slow/expensive.

If you want to make random io getting individual bytes in a file at scale, you may be better of usin mmap rather than lseek/read