File Writing and Reading

Sending text to standard output is something you learn with your first C program. The common functions are putchar(), puts(), printf(), and so on. When you explore file access, you’ll find familiarity in those functions because they’re quite similar to the standard I/O functions.

Before you can output text to a file, the file must be opened in writing or appending mode:

f = fopen(filename,"w");

The above statement opens a file. The name is represented by variable filename and the mode is "w" for write. If the file exists, it’s overwritten.

Once open, you can use file-oriented versions of the standard output functions. For example, fprintf(), which works just like the printf() function, but adds the file’s handle as the function’s first argument:

fprintf(f,"Goodbye, cruel world!\n");

The above statement writes text to the open file represented by FILE variable f. And that’s it!

Secretly (shhh!), the text is stored in a file-writing buffer, which is part of the operating system. For efficiency’s sake, data is written to files in goodly-sized chunks. Depending on the file system, the chunk could be 2K in size. The output is written when the buffer is full, manually flushed by using a special function, or when the file is closed.

The following code opens a file named output.txt, writes a string to the file, then closes the file:

#include <stdio.h>

int main()
{
    const char filename[] = "output.txt";

    FILE *f;

    /* open/create the file */
    printf("Creating '%s'\n",filename);
    f = fopen(filename,"w");
    if( f == NULL )
    {
        fprintf(stderr,"Unable to create file '%s'\n",filename);
        return(1);
    }

    /* write some text */
    fprintf(f,"This is a text file\n");
    puts("Text written");

    /* close the file */
    fclose(f);
    puts("Done");

    return(0);
}

This code is similar to the file opening and closing example from last week’s Lesson.

filename is defined as a constant character array at Line 5. It’s opened at Line 11. At Line 19, the fprintf() statement sends a line of text to the file. And the file is closed with fclose() at Line 23. All the while, various other statements output text to standard output, updating you on the progress. That way you see feedback as the program runs:

$ ./a.out
Creating 'output.txt'
Text written
Done
$ cat output.txt
This is a text file
$ 

In the terminal output (above), I used the cat command to view the file’s contents. You can also fetch the file’s contents by opening it in read mode and using the file-based version of standard input functions to extract the file’s text. The following code does that:

#include <stdio.h>

int main()
{
    const char filename[] = "output.txt";
    char buffer[64];
    FILE *f;

    /* open file for reading */
    printf("Reading from '%s'\n",filename);
    f = fopen(filename,"r");
    if( f == NULL )
    {
        fprintf(stderr,"Unable to open file '%s'\n",filename);
        return(1);
    }

    /* read text from the file */
    fgets(buffer,64,f);
    printf("File contents: %s\n",buffer);

    /* close the file */
    fclose(f);
    puts("Done");

    return(0);
}

As with the earlier code, the filename constant holds the file’s name — and it’s assumed that this file was created earlier and is a text file. A character buffer is also created at Line 6, which holds text read from the file.

At Line 11, the fopen() function opens the file in “r”, read mode. The fgets() function at Line 19 reads text from file f and stores it in buffer. The number of characters to read, 64, is the same size as the buffer; the fgets() function won’t overflow the buffer. The fclose() statement at Line 23 closes the file. And various standard output functions update the user on the program’s progress.

Here’s a sample run:

Reading from 'output.txt'
File contents: This is a text file

Done

In next week’s Lesson, I cover writing and reading larger chunks of text.

Leave a Reply