1
#include <stdio.h>

int main()
{
    FILE *fp;
    char ch;

    fp=fopen("file1.txt","r");

    while(feof(fp))
    {
        ch=fgetc(fp);
        printf("%c",ch);
    }

    return 0;
}

How does fgetc() know which character to print read (because fp remains same throughout the program, not incremented); same for how does it identify EOF? I mean, what does it actually refer to get to know where exactly it is now? How can I retrieve that memory address and print it?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
neileap
  • 63
  • 3

2 Answers2

6

A FILE * is not actually a pointer into a file which you can increment and decrement to read from; instead, it is a pointer to a struct FILE object. Different libraries have different definitions for the struct, but essentially, there are fields within the struct that will internally track the current location into the file.

Here is an example implementation of fgetc (reproduced from here):

int
fgetc(FILE *fp)
{
    int cnt;
    unsigned char c;

    if (fp->ungetcflag) {
        fp->ungetcflag = 0;
        return fp->ungetchar;
    }
    cnt = read(fp->fd, &c, 1);
    if (cnt <= 0)
        return EOF;
    return c;
}

fgetc just internally calls read to fetch the next character. You can continue down the rabbit hole and eventually find out where the struct FILE's internal state is changed to reflect having fetched a new character.

For more detail specific to your version of fgetc, you'll have to look at the source of your machine's C library.

Purag
  • 16,941
  • 4
  • 54
  • 75
3

FILE is [very likely] a data structure containing information regarding the opened (with fopen()) file. One of the structure members is the current file position (or offset) [implementation defined, but let's assume that this is the case].

Everytime you read or write to the file pointed by fp, this structure member is incremented. fseek() may be used to set the file position. ftell() will return the current file position, which, in this case, is what you're looking for.

The value of fp [a memory address] is unchanged, because, as I said, it is a pointer to a data structure [again, implementation defined, but this is probably true for every implementation] that was allocated when fopen() was invoked, and will be released when fclose() is called. What changes is the structure member values.

pah
  • 4,700
  • 6
  • 28
  • 37