Versions Compared

Key

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

...

In this noncompliant code example, more than one character is pushed back on the stream referenced by fp.

Code Block
bgColor#ffcccc
langc
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 */

...

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(). Note that this solution only applies if the input is seekable.

Code Block
bgColor#ccccff
langc
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 */

...