1.18 Re-implementing __backspace() in the C library

The function __backspace() is used by the scanf family of functions, and must be re-implemented if you retarget the stdio arrangements at the fgetc() level.

Note:

Normally, you are not required to call __backspace() directly, unless you are implementing your own scanf-like function.

The syntax is:

int __backspace(FILE *stream);

__backspace(stream) must only be called after reading a character from the stream. You must not call it after a write, a seek, or immediately after opening the file, for example. It returns to the stream the last character that was read from the stream, so that the same character can be read from the stream again by the next read operation. This means that a character that was read from the stream by scanf but that is not required (that is, it terminates the scanf operation) is read correctly by the next function that reads from the stream.

__backspace is separate from ungetc(). This is to guarantee that a single character can be pushed back after the scanf family of functions has finished.

The value returned by __backspace() is either 0 (success) or EOF (failure). It returns EOF only if used incorrectly, for example, if no characters have been read from the stream. When used correctly, __backspace() must always return 0, because the scanf family of functions do not check the error return.

The interaction between __backspace() and ungetc() is:

  • If you apply __backspace() to a stream and then ungetc() a character into the same stream, subsequent calls to fgetc() must return first the character returned by ungetc(), and then the character returned by __backspace().

  • If you ungetc() a character back to a stream, then read it with fgetc(), and then backspace it, the next character read by fgetc() must be the same character that was returned to the stream. That is the __backspace() operation must cancel the effect of the fgetc() operation. However, another call to ungetc() after the call to __backspace() is not required to succeed.

  • The situation where you ungetc() a character into a stream and then __backspace() another one immediately, with no intervening read, never arises. __backspace() must only be called after fgetc(), so this sequence of calls is illegal. If you are writing __backspace() implementations, you can assume that the ungetc() of a character into a stream followed immediately by a __backspace() with no intervening read, never occurs.

Non-ConfidentialPDF file icon PDF versionARM DUI0475M
Copyright © 2010-2016 ARM Limited or its affiliates. All rights reserved.