0

Hi all, I'm new to system programming. I wanted to read from a file into a buffer (say, buf[BUFSIZ]), from the end to the beginning. For example, if the file contains "Hello", then the buffer will contain "olleH". I know lseek() will reposition the opened file offset. I just tried lseek(fd, -6, 2), but the result is still "Hello". I don't know why. Please help, thank you very much!

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by jephthah
0

Even though what you want to do makes no sense,

1- Use lseek() to get to the end of the file.
2- lseek() back one character
3- read the character
4- repeat 2&3 until you get to the beginning of the file

0

yeah, lseek doesnt read backwards. because seek doesnt read. seek just moves the file pointer to a relative position. lseek moves it to the "left" (ie, backwards)

file reads are always done in the forward sequence.

a better way to read something in reverse, is to first read it from the file as normal, into a character buffer in memory, then copy it backwards into your target buffer by decrementing the index or pointer.

walt's suggestion is very literal minded. Like the genie in the lamp granting wishes, he gave you exactly what you asked. it would be a huge resource hog for any sizeable file.


.

Edited by jephthah: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.