Is EOF always negative?

后端 未结 6 1941
被撕碎了的回忆
被撕碎了的回忆 2020-12-11 17:05

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

6条回答
  •  盖世英雄少女心
    2020-12-11 17:36

    From the online draft n1256, 17.9.1.3:

    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;

    EOF is always negative, though it may not always be -1.

    For issues like this, I prefer separating error conditions from data by returning an error code (SUCCESS, END_OF_FILE, READ_ERROR, etc.) as the function's return value, and then writing the data of interest to separate parameters, such as

    int getNextWord (FILE *stream, char *buffer, size_t bufferSize, int *lineNumber)
    {
      if (!fgets(buffer, bufferSize, stream))
      {
        if (feof(stream)) return END_OF_FILE; else return READ_ERROR;
      }
      else
      {
        // figure out the line number
        *lineNumber = ...;
      }
      return SUCCESS;
    }      
    

提交回复
热议问题