Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is EOF always negative?

Tags:

c

eof

Is EOF always negative?

I'm thinking of writing a function that reads the next word in the input and returns the line number the word was found in or EOF if the end of the input has been reached. If EOF is not necessarily negative, the function would be incorrect.

like image 900
Ree Avatar asked Oct 26 '09 10:10

Ree


People also ask

Can EOF be negative?

From wikipedia : The actual value of EOF is a system-dependent negative number, commonly -1, which is guaranteed to be unequal to any valid character code.

How is EOF represented?

The EOF is commonly represented by pressing and holding Ctrl and pressing Z in DOS and OS/2 or pressing and holding Ctrl and pressing D in Unix. With many PC programs, you can get to the end of a file by pressing the shortcut key Ctrl + End .

What is EOF value?

The value of EOF is a negative integer constant. The precise value is implementation-defined.

What type of value is EOF () returning?

An EOF return value indicates an error or an end-of-file condition. Use the feof() or the ferror() function to determine whether the EOF value indicates an error or the end of the file.


2 Answers

EOF is always == EOF. Don't assume anything else.

On a second reading of the standard (and as per some other comments here) it seems EOF is always negative - and for the use specified in this question (line number or EOF) it would work. What I meant to warn against (and still do) is assuming characters are positive and EOF is negative.

Remember that it's possible for a standard conforming C implementation to have negative character values - this is even mentioned in 'The C programming language' (K&R). Printing characters are always positive, but on some architectures (probably all ancient), control characters are negative. The C standard does not specify whether the char type is signed or unsigned, and the only character constant guaranteed to have the same value across platforms, is '\0'.

like image 104
gnud Avatar answered Sep 25 '22 11:09

gnud


Yes, EOF is always negative.

The Standard says:

7.19 Input/output
7.19.1 Introduction

3 The macros are [...] EOF which expands to an integer constant expression, with type int and a negative value, that is returned by several functions to indicate end-of-file, that is, no more input from a stream;

Note that there's no problem with "plain" char being signed. The <stdio.h> functions which deal with chars, specifically cast the characters to unsigned char and then to int, so that all valid characters have a positive value. For example:

int fgetc(FILE *stream)

7.19.7.1
... the fgetc function obtains that character as an unsigned char converted to an int ...

like image 29
pmg Avatar answered Sep 22 '22 11:09

pmg