Opening and Closing of File Streams in C

What is a File Stream in C?

In C, a file stream is a way to read from or write to a file. When you open a file, you create a connection (or stream) between the program and the file stored on disk. Once you’re done, you need to close that connection properly.

Opening a File Stream

To open a file, C provides the fopen() function from the stdio.h library.

Syntax:

FILE *fopen(const char *filename, const char *mode);
  • filename: Name of the file to open.
  • mode: Operation mode (e.g., read, write).

Common File Modes

Mode Description
“r” Open for reading (file must exist)
“w” Open for writing (creates/truncates file)
“a” Open for appending
“r+” Open for reading and writing
“w+” Create for read/write
“a+” Append for read/write

Example: Opening a File for Writing

#include <stdio.h>
 
int main() {
    FILE *quiz;
    quiz = fopen("example.txt", "w");  // Opening for writing
 
    if (quiz == NULL) {
        printf("Error opening file!\n");
        return 1;
    }
 
    fprintf(quiz, "Sanfoundry C File Stream Example\n");
 
    fclose(quiz);  // Closing the file
    printf("File written and closed successfully.\n");
 
    return 0;
}

Output:

File written and closed successfully.

This C program writes text to a file. It opens “example.txt” in write mode using fopen(). If the file can’t be opened, it shows an error and exits. If successful, it writes a line to the file using fprintf(), then closes the file with fclose(). A success message is printed at the end.

advertisement

Closing a File Stream

After completing file operations, it’s crucial to close the file using fclose() to free resources and ensure data integrity.

Syntax:

int fclose(FILE *stream);

stream: Pointer to the opened file.

Free 30-Day Python Certification Bootcamp is Live. Join Now!

Example:

fclose(file);

Always check the return value of fclose() to handle potential errors.

Example: Reading from a File

#include <stdio.h>
 
int main() {
    FILE *quiz;
    char str[100];
 
    quiz = fopen("example.txt", "r");  // Opening for reading
    if (quiz == NULL) {
        printf("File not found!\n");
        return 1;
    }
 
    while (fgets(str, sizeof(str), quiz) != NULL) {
        printf("Read Line: %s", str);
    }
 
    fclose(quiz);  // Important to close the file
 
    return 0;
}

Output:

Read Line: Sanfoundry C File Stream Example

This C program reads text from a file. It opens “example.txt” in read mode using fopen(). If the file doesn’t exist, it prints an error and exits. If opened successfully, it reads each line using fgets() and prints it. After reading, the file is closed with fclose().

Error Handling in File Operations

  • Opening Files: Always check that fopen() does not return NULL. If it does, the file couldn’t be opened.
  • Reading/Writing: Use return values of functions like fgetc(), fgets(), fread(), and fwrite() to detect any read/write errors.
  • Closing Files: Confirm that fclose() returns 0, which means the file closed successfully.

Advanced File Operations in C

Advanced file operations go beyond simple reading and writing. These include:

  • Reading/Writing binary files.
  • Random file access (using fseek(), ftell(), rewind()).
  • File status (e.g., end-of-file, errors).
  • Temporary file handling.
  • Formatted I/O with fscanf()/fprintf().

Random Access with fseek(), ftell(), rewind()

advertisement

1. fseek(): Set the file position indicator.

int fseek(FILE *stream, long int offset, int origin);

origin: SEEK_SET, SEEK_CUR, SEEK_END

2. ftell(): Return current file position.

long int ftell(FILE *stream);

3. rewind(): Set position to beginning.

void rewind(FILE *stream);

Example:

#include <stdio.h>
 
int main() {
    FILE *quiz = fopen("sanfoundry.txt", "w+");
    if (!quiz) {
        printf("File opening failed\n");
        return 1;
    }
 
    fprintf(quiz, "Sanfoundry Quiz on C\n");
 
    rewind(quiz);  // Go back to beginning
 
    char line[50];
    fgets(line, sizeof(line), quiz);
    printf("Line Read: %s", line);
 
    fseek(quiz, 0, SEEK_END);
    long pos = ftell(quiz);
    printf("\nFile size: %ld bytes\n", pos);
 
    fclose(quiz);
    return 0;
}

Output:

Line Read: Sanfoundry Quiz on C
File size: 22 bytes

Binary File I/O with fwrite() and fread()

Syntax:

size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
size_t fread(void *ptr, size_t size, size_t count, FILE *stream);

Example:

#include <stdio.h>
 
struct student {
    int id;
    float score;
};
 
int main() {
    struct student s1 = {101, 98.5};
    FILE *fp = fopen("student.dat", "wb");
 
    fwrite(&s1, sizeof(s1), 1, fp);
    fclose(fp);
 
    struct student s2;
    fp = fopen("student.dat", "rb");
    fread(&s2, sizeof(s2), 1, fp);
    fclose(fp);
 
    printf("ID: %d, Score: %.1f\n", s2.id, s2.score);
    return 0;
}

Output:

ID: 101, Score: 98.5

This C program writes and reads a structure to/from a binary file. It creates a student structure and writes it to “student.dat” using fwrite(). Then, it reads the structure back with fread() into another variable. Finally, the program prints the student’s ID and score, confirming the file operations.

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

If you wish to look at all C Tutorials, go to C Tutorials.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.