Solution for Exercise 22-1

ex2201

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

int main()
{
    FILE *fh;

    fh=fopen("hello.txt","w");
    if(fh==NULL)
    {
        puts("Can't open that file!");
        exit(1);
    }
    fprintf(fh,"Look what I made!\n");
    fclose(fh);
    return(0);
}

Notes

* The file created, hello.txt, is most likely found in the same directory in which the source code or executable for this Exercise is located. When using Code::Blocks, hello.txt is found in the project's main folder, where the source code file is located.

* The FILE thing is a typedef, defined in the the stdio.h header file. FILE a structure, always used as a pointer in your code. Call it the "file handle" variable.

* Always use fclose() when you're done working with a file. It's true that the operating system cleans up any lingering files should your program quit before closing. If that happens, however, you run the risk of losing information that hasn't yet been written to the file.