Solution for Exercise 22-1

ex2201

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

int main()
{
    FILE *fh;

    /* open the file */
    fh=fopen("hello.txt","w");
    /* check for errors */
    if(fh==NULL)
    {
        puts("Can't open that file!");
        exit(1);
    }
    /* output text */
    fprintf(fh,"Look what I made!\n");
    /* close the file */
    fclose(fh);
    /* inform the user */
    puts("File written.");
    return(0);
}

Output

File written.

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 this happens, however, you run the risk of losing information that hasn't yet been written to the file. (File I/O is buffered.)