1

I'm new to C, and have been staring at this code for a while:

void readEntireFile(){
    int ch;
    FILE *fp;  // pointer to a file type
    fp = fopen("/some/path/file", "r"); // Change to match your path
    ch = getc(fp);
    while (ch != EOF){  // keep looping until End Of File
        putchar(ch);    // print the characters read
        ch = getc(fp);
    }
    fclose(fp);
}

This function creates a pointer to a file, gets the first character, and as long as the character isn't an EOF char, prints the char. This continues until the EOF character is reached.

My question here is simple: how come the pointer continues to point to the next character each time? I can't see how it's incremented, and am getting really confused!

EDIT: in addition the answer below, this question also helped me understand.

scrollex
  • 2,575
  • 7
  • 24
  • 38
  • 1
    `FILE` is a platform-dependent structure holding, among other things, access to the descriptor (or whatever the platform uses for file access), buffering, etc. the `FILE*` isn't being incremented or changed. The data *within* that pointed-to object may be (especially if buffered), and done through the file io functions of the standard library – WhozCraig Sep 13 '18 at 23:06

1 Answers1

5

int getc ( FILE * stream ); gets a character from the stream.

It returns the character currently pointed by the internal file position indicator of the specified stream. The internal file position indicator is then advanced to the next character. (The increment.) Which is this line specfically:

ch = getc(fp);

Rivasa
  • 6,510
  • 3
  • 35
  • 64