man fflush
on Ubuntu:
For input streams associated with seekable files (e.g., disk files, but not pipes or terminals),
fflush()
discards any buffered data that has been fetched from the underlying file, but has not been consumed by the application.
I've read some questions talking about fflush(stdin)
and fflush()
a input stream is undefined behaviour according to the standard, that's right. But for Linux specifically, I've read comments says that it's not a undefined behaviour but an extension, yes, the manpage above says how it would work on a file input stream.
So, why fflush()
a input filestream does not discard buffered data that has been fetched from the underlying file, but has not been consumed by the application. as the manpage describes ?
Before searching on the Web I fully believe the manpage now I want to know if it's wrong.
Sample code:
haha2.txt: 123456
, no line feed or whitespace.
#include <stdio.h>
int
main()
{
FILE* fp = fopen("haha2.txt", "r");
int q = getc(fp);
fflush(fp);
int j = getc(fp); // I expect the rest variables to be -1(EOF) starting from here
int j2 = getc(fp);// But they can still read data as if fflush does not executed
int j3 = getc(fp);
int j4 = getc(fp);
int j5 = getc(fp);
int j6 = getc(fp);
int j7 = getc(fp);
int j8 = getc(fp);
printf("%c,%c,%c,%c,%c,%c,%c,%c\n", j,j2,j3,j4,j5,j6,j7,j8);
return(0);
}
fflush
behavior is specific to Linux. Why don't you useungetc
? – Idyllic123456
in file, buffer is3
, for the first time it reads123
into the buffer and somehow dicard the buffer, will the system read456
next time or start from the beginning again, which still reads123
? Thanks – Bonaventuregetc
to test if the buffer is discarded or not. Why useungetc
? – Bonaventure_IO_read_ptr
and_IO_read_end
pointers to see what was buffered. I don't know whether the buffer data was dicarded, the manpage says so and I just believe it (cause I don't know how it internally works), but I don't know how the next read will operate, starts before discarded place, or starts after discarded position, that what I don't know. – Bonaventurestdin
instead offp
. Then you can type something on the keyboard and press enter. If the code does a few reads and callsfflush(stdin)
, the rest of the line should be discarded. – Obelizefflush
on a disk file (that is not still being written to). It only makes sense to me as user3386109 to clear out unwanted keyboard input: for example if you have asked an important question and you want to ensure there is no type-ahead buffered. – Klaxonfflush()
, which correct my understanding.. – Bonaventurereadline
– Idyllic