Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The ungetc() function pushes a character onto an input stream. This pushed character can then be read by subsequent calls to functions that read from that stream. However, the ungetc() function has serious limitations. A call to a file positioning function, such as fseek(), will discard any character pushed back by ungetc(). Also, the C standard only guarantees that the pushing back of one character will succeed. Therefore, subsequent calls to ungetc() must be separated by a call to a read function or a file-positioning function (which will discard any data pushed by ungetc()). If more than one character needs to be pushed by ungetc(), then fgetpos() and fsetpos() should be used before and after reading the data instead of pushing it back with ungetc().

Non-Compliant Code Example

Code Block
bgColor#ffcccc
FILE* fptr = fopen(file_name, "rb");
if (fptr == NULL) {
  /* handle error condition */
}

/* Read data */

ungetc('\n', fptr);
ungetc('\r', fptr);

/* Continue on */

Compliant Solution

If more than one character needs to be pushed by ungetc(), then fgetpos() and fsetpos() should be used before and after reading the data instead of pushing it back with ungetc().

Code Block
bgColor#ccccff
FILE* fptr = fopen(file_name, "rb");
fpos_t pos;

if (fptr == NULL) {
  /* handle error condition */
}

if(fgetpos(fptr, &pos)) {
  /* Handle Error */
}

/* Read data */

if(fsetpos(fptr, &pos)) {
  /* Handle Error */
}

/* Continue on */

...