0
0
Cprogramming~5 mins

File pointers in C

Choose your learning style9 modes available
Introduction

File pointers help your program find and work with files on your computer. They keep track of where you are inside a file.

When you want to read data from a file, like a list of names.
When you want to save information to a file, like saving game scores.
When you want to update or change parts of a file without rewriting the whole file.
When you want to check if a file exists or open it safely.
When you want to move around inside a file to read or write at different places.
Syntax
C
FILE *pointer_name;
pointer_name = fopen("filename", "mode");

FILE * is a special type that points to a file.

fopen opens the file and returns the pointer.

Examples
Open data.txt for reading and save the pointer in fp.
C
FILE *fp;
fp = fopen("data.txt", "r");
Open output.txt for writing. If the file does not exist, it will be created.
C
FILE *fp = fopen("output.txt", "w");
Open log.txt for appending. New data will be added at the end.
C
FILE *fp = fopen("log.txt", "a");
Sample Program

This program creates a file called example.txt, writes a message, closes it, then reopens it to read and print the message.

C
#include <stdio.h>

int main() {
    FILE *fp = fopen("example.txt", "w");
    if (fp == NULL) {
        printf("Failed to open file.\n");
        return 1;
    }
    fprintf(fp, "Hello, file pointers!\n");
    fclose(fp);

    fp = fopen("example.txt", "r");
    if (fp == NULL) {
        printf("Failed to open file for reading.\n");
        return 1;
    }
    char buffer[100];
    if (fgets(buffer, sizeof(buffer), fp) != NULL) {
        printf("Read from file: %s", buffer);
    }
    fclose(fp);
    return 0;
}
OutputSuccess
Important Notes

Always check if fopen returns NULL to avoid errors if the file can't be opened.

Use fclose to close files and free resources when done.

File pointers remember where you are in the file for reading or writing.

Summary

File pointers let your program open and work with files.

You use fopen to open a file and get a pointer.

Always close files with fclose when finished.