Question on fseek optimization in newlib

Can Finner
Tue Jun 19 13:12:00 GMT 2012

In function _fseek_r, it seems for buffered file(opened for writing),
newlib always decrease "curoff" by n(=fp->_p - fp->_bf._base).
The variable “curoff” is returned by “seekfn (ptr, fp->_cookie, 0L,
SEEK_CUR)”, which should be __seek.
My question is why should we decrease “curoff” by “n”, in my
understanding, the file position returned by __seek/lseek does
not include bytes in writing buffer.

For example,
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(void)
    FILE *pfile;
    off_t p1, p2;
    int fd = open("lseek.temp", O_WRONLY | O_CREAT | O_TRUNC,
    pfile = fdopen(fd, "w");
    setvbuf(pfile, NULL, _IOFBF, 1024);
    fwrite("hello world\n", 1, 10, pfile);
    p1 = lseek (fd, 0, SEEK_CUR);
    fflush (pfile);
    p2 = lseek (fd, 0, SEEK_CUR);
    fprintf(stdout, "p1 = %u\np2 = %u\n", (unsigned int)p1, (unsigned int)p2);
    return 0;
The output is:
p1 = 0
p2 = 10

Thought I got the output on linux with glibc, I assume same story with newlib.

So, did I miss something important? Please help.

Thanks in advance.


More information about the Newlib mailing list