feof()實際上是如何知道文件結束的時間?
當代碼試圖讀取通過最後一個字符。
根據文件類型的不同,最後一個字符必須知道,直到嘗試讀取它過去並且沒有字符可用。
樣本代碼演示feof()
打算從0到1個
#include <stdio.h>
void ftest(int n) {
FILE *ostream = fopen("tmp.txt", "w");
if (ostream) {
while (n--) {
fputc('x', ostream);
}
fclose(ostream);
}
FILE *istream = fopen("tmp.txt", "r");
if (istream) {
char buf[10];
printf("feof() %d\n", feof(istream));
printf("fread %zu\n", fread(buf, 1, 10, istream));
printf("feof() %d\n", feof(istream));
printf("fread %zu\n", fread(buf, 1, 10, istream));
printf("feof() %d\n", feof(istream));
puts("");
fclose(istream);
}
}
int main(void) {
ftest(9);
ftest(10);
return 0;
}
輸出
feof() 0
fread 9 // 10 character read attempted, 9 were read
feof() 1 // eof is set as previous read attempted to read passed the 9th or last char
fread 0
feof() 1
feof() 0
fread 10 // 10 character read attempted, 10 were read
feof() 0 // eof is still clear as no attempt to read passed the 10th, last char
fread 0
feof() 1
http://stackoverflow.com/questions/4358728/end-of-file-eof-in-c希望這會有所幫助:) – kartik7153
圖像流沒有已知的限制。然後,沒有其他方法可以嘗試讀取文件的結尾。 (注意文件流是不同類型輸入/輸出的抽象) –
@ kartik7153不能回答他的問題。他詢問操作系統是如何特別決定文件何時到達的。 – Creris