Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

c - fgetc(): Is it enough to just check EOF?

In various examples found on the web fgetc() is used like this:

FILE *fp = fopen(PATH, "r");

if (fp == NULL) {
    perror("main");
    exit(EXIT_FAILURE);
}

int ch;

while (ch = fgetc(fp) != EOF) {
    // do something
}

But according to the manpage to fgetc()

If a read error occurs, the error indicator for the stream shall be set, fgetc() shall return EOF, [CX] and shall set errno to indicate the error.

So need I check this too? And how?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is what the specs say:

the fgetc() function shall obtain the next byte as an unsigned char converted to an int

The following macro name shall be defined as a negative integer constant expression: EOF

As long as you store the return value in an int and not a char, it is sufficient to check for EOF because it is guaranteed not to represent a valid character value.


Also, in your code, this:

while (ch = fgetc(fp) != EOF)

should be:

while ((ch = fgetc(fp)) != EOF)

The additional parentheses are required because != has higher precedence than =.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...