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

Output

Look what I made!
My C program wrote this file.

Notes

* The output is based on the contents of the hello.txt file. If you've completed the Exercises for Chapter 22 in sequence, the output appears as shown above.

* Another way to write the while loop is:

Here, the return value from fgets() is evaluated directly in the while loop; NULL is interpreted as FALSE.

* Any text not read from the file into the buffer sits and waits its turn. The next time fgets() is called with the same file handle, new characters are read. For example, if a sentence read is split by fgets(), 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.

* Last time I checked, the operating system buffers file input in 2K (2048-byte) chunks.