fxlibc/src/libc/stdio/fflush.c

43 lines
869 B
C

#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include "fileutil.h"
int fflush(FILE *fp)
{
/* TODO: fflush(NULL) should flush "all" files (do we track them?) */
if(!fp) {
errno = EINVAL;
return EOF;
}
if(!fp->buf)
return 0;
int rc = 0;
/* In reading mode, reset the file offset */
if(__fp_hasbuf_read(fp)) {
fp->fdpos = fp->fdpos - fp->bufread + fp->bufpos;
lseek(fp->fd, fp->fdpos, SEEK_SET);
}
/* In writing mode, write pending data */
else if(__fp_hasbuf_write(fp)) {
ssize_t written = __fp_write(fp, fp->buf, fp->bufpos);
rc = (written == (ssize_t)fp->bufpos ? 0 : EOF);
/* TODO: fflush(): Keep data that couldn't be written */
}
fp->bufpos = 0;
fp->bufread = 0;
fp->bufungetc = 0;
/* Clear buffering for unbuffered streams that used ungetc() */
if(fp->bufmode == _IONBF)
__fp_remove_buffer(fp);
return rc;
}