Section 7.1921.7.11 of C99 defines ungetc()
as follows 10 of C11 [ISO/IEC 9899:1999]2011] defines ungetc()
as follows:
The
ungetc
function pushes the character specified byc
(converted to anunsigned char
) back onto the input stream pointed to bystream
. Pushed-back characters will be returned by subsequent reads on that stream in the reverse order of their pushing. A successful intervening call (with the stream pointed to bystream
) to a file positioning function (fseek
,fsetpos
, orrewind
) discards any pushed-back characters for the stream. The external storage corresponding to the stream is unchanged.One character of pushback is guaranteed.
Consequently, multiple calls to ungetc()
on the same stream must be separated by a call to a read function or a file-positioning function (which will discard any data pushed by ungetc()
).
Likewise, for ungetwc()
, C99 C guarantees only guarantees one wide character of pushback (Section 7.2429.3.10). Consequently, multiple calls to ungetwc()
on the same stream must be separated by a call to a read function or a file-positioning function (which will discard any data pushed by ungetwc()
).
...
Code Block | ||||
---|---|---|---|---|
| ||||
FILE *fp;
char *file_name;
/* initialize file_name */
fp = fopen(file_name, "rb");
if (fp == NULL) {
/* Handle error */
}
/* read data */
if (ungetc('\n', fp) == EOF) {
/* Handle error */
}
if (ungetc('\r', fp) == EOF) {
/* Handle error */
}
/* continue on */
|
...
Code Block | ||||
---|---|---|---|---|
| ||||
FILE *fp;
fpos_t pos;
char *file_name;
/* initialize file_name */
fp = fopen(file_name, "rb");
if (fp == NULL) {
/* Handle error */
}
/* read data */
if (fgetpos(fp, &pos)) {
/* Handle error */
}
/* read the data that will be "pushed back" */
if (fsetpos(fp, &pos)) {
/* Handle error */
}
/* Continue on */
|
Remember to always call fgetpos()
before fsetpos()
. (See rule FIO44-C. Only use values for fsetpos() that are returned from fgetpos().)
...
Tool | Version | Checker | Description | ||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
Section | Compass/ROSE |
|
| Section | Can detect simple violations of this recommendation. In particular, it warns when two calls to It cannot handle cases where . | ||||||
| Section | 83 D Section | | Fully Implementedimplemented. |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
ISO/IEC 9899:1999 Section 2011 Section 7.1921.7.1112, "The ungetc
function," and Section 7.29.3.10, "The ungetwc
function"
Bibliography
...