How do I distinguish between an EOF character, and

2020-03-23 17:55发布

When reading a file, I understand the last character provided is an EOF. Now, what happens, when I have an EOF character in that file?

How do I distinguish between the "real" end of a file, and the EOF character?

标签: eof
3条回答
▲ chillily
2楼-- · 2020-03-23 18:24

Assuming you're talking about C, EOF is -1, which is not a character (hence there is no confusion).

查看更多
Bombasti
3楼-- · 2020-03-23 18:28

I decided to move my comments to an answer.

You can't have an "EOF character" in your file because there is no such thing. The underlying filesystem knows how many bytes are in a file; it doesn't rely on the contents of the file to know where the end is.

The C functions you're using return EOF (-1) but that wasn't read from the file. It's just the way the function tells you that you're reached the end. And because -1 isn't a valid character in any character set, there's no confusion.

查看更多
甜甜的少女心
4楼-- · 2020-03-23 18:35

You need some context for this question. On Windows, there's the outdated DOS concept of a real "EOF character" -- Ctrl-Z. It is actually not possible to tell a "real" one from a "fake" one; a file with an embedded Ctrl-Z will contain some trailing hidden data from the perspective of a program which is actually looking for Ctrl-Z as an end of file character. Don't try to write this kind of code anymore -- it's not necessary.

In the portable C API and on UNIX, a 32-bit -1 is used to indicate end of file, which can't be a valid 8 or 16-bit character, so it's easy to tell the difference.

查看更多
登录 后发表回答