feof() 函数和 C 文件的 EOF 有什么区别?

问题描述 投票:0回答:2

我不明白

feof()
函数和
EOF
有什么区别?两者都代表文件结尾,那么它们有何不同,我们如何知道在哪里使用什么?

在哪里使用

feof()
功能和在哪里使用
EOF
?

c file eof feof
2个回答
1
投票

feof
EOF
<stdio.h>
中定义。

EOF
是一个扩展为具有负值(通常为
int
)的
-1
类型的整数常量表达式的宏。它不同于
getchar()
getc()
fgetc()
返回的所有有效字节值。如果无法从流中读取任何字节,这些函数将返回
EOF
。必须将返回值存储到
int
中,以便与
EOF
进行比较,以可靠地检测文件结尾。

关于

feof()
,快速回答是:

永远不要使用

feof(file)
,总是检查所有文件读取函数的返回值以检测流的结束:

对于

getchar()
getc()
fgetc()

int c;
while ((c = getchar()) != EOF) {
    // handle the byte read from the file
}
// end of file reached

对于

fgets()

char buf[100];
if (fgets(buf, sizeof buf, file)) {
    // a line was read into buf, or the initial portion of
    // the current line if longer than 99 bytes.
} else {
    // end of file has been reached.
}

对于

fread()

size_t nread = fread(buf, size_of_element, count_of_elements, file);
if (nread > 0) {
    // handle the elements read
} else {
    // end of file reached
}

对于

scanf()
fscanf()

int value;
if (fscanf(file, "%d", &value) == 1) {
    // int value was read from the stream
} else {
    // no integer could be read: either input is not an integer or
    // end of file was reached.
    // read and discard the input line
    int c;
    while ((c = getc(file)) != EOF && c != '\n')
        continue;
    if (c == EOF) {
        // end of file reached
    } else {
        // try and recover from invalid input.
    }
}

你可能想阅读和理解为什么“while(!feof(file))”总是错误的?.

长答案是:

feof()
函数返回文件结束指示符的值,该指示符可能已在到达文件末尾时由先前的文件读取操作设置。由于您应该始终测试这些文件读取操作是否成功,因此很少使用此函数,仅用于区分文件读取错误和到达文件末尾。文件读取错误在今天的桌面系统上非常少见,因此这种区分通常是不必要的。 99% 使用
feof()
的代码都在滥用这个函数。


0
投票

函数

feof(file)
如果前一个文件操作设置了文件结束标志则返回TRUE。

EOF
是许多文件 I/O 函数返回的整数常量,表示无法从文件/流中读取更多数据。

feof()函数在哪里使用,of在哪里使用?

基本上你可以使用

feof(file)
after I/O 操作来检查是否设置了文件结束标志(即是否可以从文件/流中读取更多数据)

EOF 由许多 I/O 函数返回 - 您需要阅读函数文档。例子fscanf

© www.soinside.com 2019 - 2024. All rights reserved.