Solution for Exercise 22-4

ex2204

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fh;
    char buffer[64];

    fh=fopen("hello.txt","r");
    if(fh==NULL)
    {
        puts("Can't open that file!");
        exit(1);
    }
    while(fgets(buffer,64,fh))
        printf("%s",buffer);
    fclose(fh);
    return(0);
}

Notes

* As I stated in the book's errata, the \0 isn't read from the file because it's not saved to the file. The \0 isn't used as the EOF marker.

* The fgets() function stops reading text when the EOF is encountered or after the newline character, \n, is read.

* You don't have to size the fgets() buffer to exactly match the information read from the file. Unlike text input from the keyboard, fgets() may fill the input buffer over and over. Any text not read into the buffer sits and waits in the stream for its turn; the next time fgets() is called, the characters are read. If a sentence is split, then it's glued together again when it's output.

* It's efficient to use a Holy Computer Number when reading information from a file. For a small file, like hello.txt, I chose the value 64. For a larger file, I'd probably use values 512 or 1024 to read in chunks of information.

* A Holy Computer Number is a power of 2: 2, 4, 8, 16, 32, 64, 128, and so on.