Tree
Tree

Reputation: 145

Why should fseek be called with offset of -2 instead an offset of -1 in the program that prints the text file backwards?

The following C program prints a text file backwards:

#include <stdio.h>
#define SEEK_SET 0
#define SEEK_CUR 1
#define SEEK_END 2
int main(int argc, char **argv)
{
    FILE *fp = f
   open(argv[1], "r");
   fseek(fp, -1L, SEEK_END);
   while (ftell(fp)) 
   {
      putchar(fgetc(fp));
       fseek(fp, -2L, SEEK_CUR);
   }

putchar(fgetc(fp));

Since the program is supposed to print the text file backwards, it is supposed to read each and every character from the end, without skipping any characters. If so,I thought the call within the while loop should be

fseek(fp, -1L, SEEK_CUR);

How come the offset is -2 and not -1?

Thanks in advance!

Upvotes: 0

Views: 795

Answers (1)

Luis Cabrero
Luis Cabrero

Reputation: 66

When you call fgetc, offset goes 1 char ahead of what you expect, so you need to move 2 back to get the char you expect to get. Otherwise you would be getting the same char all the time.

Upvotes: 1

Related Questions