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.

1
  • 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 Commented Sep 13, 2018 at 23:06

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.