I have this code and I don't understand how it works:
void print(char * fileName)
{
FILE * fp;
int ch;
fp = fopen(fileName, "r");
while (ftell(fp) < 20)
{
ch = fgetc(fp);
putchar(ch);
}
fclose(fp);
}
How does ftell(fp) work in the loop? Because there is nothing inside the loop that get it up. How it is progressive?
ftell()gets you the current value of the position indicator of the stream(in your case, it basically returns the character position it is currently pointing to right now).fgetc()gets the next character (an unsigned char) from the specified stream and advances the position indicator for the stream. This function returns the character read as an unsigned char cast to an int or EOF on end of file or errorFlow of your program
What that means in very simple terms is -
fgetc()is reading one character after character from the file and advancing the pointer to the next character.ftell()is returning you the current position in in bytes from the beginning of the file. This means it tells the position of the character it is pointing right now(since 1 char takes 1 byte).So, your program reads from the file until
ftell()returns the position which is less than 20.This means that it will keep looping until 20 characters have been read from your file.Hope this clears your doubt !