Skip to main content

Opening and closing a data file

Short answer

Opening a file with fopen connects a disk file to a FILE pointer, specifying mode (r, w, a). Always check for NULL. Closing with fclose flushes buffers, releases resources, and prevents data loss.

What do you mean by opening a data file? How is this accomplished? Define opening and closing a file along with suitable examples.

Opening a file

Opening a file means connecting a file on the disk to a program through a file pointer, so that the program can read from or write to it. The function fopen() does this:

FILE *fp = fopen("filename", "mode");

It returns the file pointer, or NULL if the file cannot be opened (for example, a file for reading does not exist), so the result must always be checked. Common modes: "r" read, "w" write (creates/erases), "a" append.

Closing a file

fclose(fp); disconnects the file: it writes the remaining buffered data to the disk, releases the file pointer and the resources of the system, and prevents data loss. The number of files that can be open at one time is limited, so files should be closed when work is finished.

#include <stdio.h>

int main(void)
{
    FILE *fp;                              /* file pointer */

    fp = fopen("data.txt", "w");           /* open for writing */
    if (fp == NULL) {                      /* check that opening succeeded */
        printf("Unable to open the file\n");
        return 1;
    }
    fprintf(fp, "Hello file\n");
    fclose(fp);                            /* close: flush buffer, free the file */
    printf("File written and closed\n");
    return 0;
}

Output: File written and closed

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 10 questions →