The ungetc()
function allows for the pushes characters onto an input stream. These pushed character will then be read by subsequent calls to read. However, the ungetc()
function has serious limitations. A call to a file positioning function, such as fseek()
, will discard any character pushed on 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 an update stream should be used.
Non-Compliant Code Example
FILE* fptr = fopen("myfile.ext", "rb"); if (fptr == NULL) { /* handle error condition */ } /* Read data */ ungetc('\n', fptr); ungetc('\r', fptr); /* Continue on */
Compliant Solution
(none known)
Risk Assessment
The limitations of ungetc()
can cause data to be truncated or lost.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
FIO13-A |
1 (low) |
2 (probable) |
1 (high) |
P2 |
L3 |
Reference
[[ISO/IEC 9899-1999:TC2]] Section 7.19.7.11, "The ungetc
function"