Member Avatar for philipghu

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!

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

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.


.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.