Versions Compared

Key

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

...

Code Block
bgColor#ffcccc
FILE *fp;
char *file_name;

/* initialize file_name */

fp = fopen(file_name, "rb");
if (fp == NULL) {
  /* handleHandle Errorerror */
}

/* read data */

if (ungetc('\n', fp) == EOF) {
  /* handleHandle error */
}
if (ungetc('\r', fp) == EOF) {
  /* handleHandle 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 can only be used applies if the input is seekable.

Code Block
bgColor#ccccff
FILE *fp;
fpos_t pos;
char *file_name;

/* initialize file_name */

fp = fopen(file_name, "rb");
if (fp == NULL) {
  /* handleHandle Errorerror */
}

/* read data */

if (fgetpos(fp, &pos)) {
  /* handleHandle Errorerror */
}

/* read the data that will be "pushed back" */

if (fsetpos(fp, &pos)) {
  /* handleHandle Errorerror */
}

/* Continue on */

Remember to always call fgetpos() before fsetpos() (see FIO44-C. Only use values for fsetpos() that are returned from fgetpos()).

...