• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » C » File » The fclose Function in C
Next →
← Prev

The fclose Function in C

By Dinesh Thakur

When I/O operations on a file are complete, we must close the file using the fclose function. The prototype of this function is as follows:

int fclose ( FILE *fP ) ;

The argument fp is a pointer to the file to be closed. This pointer is initialized when the file is opened. The function returns a zero value when a file is closed successfully; otherwise, it returns EOF.

When fclose is called with a file opened for an output or update operation, the contents of the file buffer are flushed, i. e., they are written to the file, the buffer is de-allocated and the file is closed. On the other hand, when fclose is called with a file opened for buffered input, the buffer is de-allocated (its contents are discarded) and the file is closed.

Example of Opening and closing a file

The program segment given below illustrates how a file specified by the user is opened as a text file for input and closed after the input operations are over.

#include <stdio.h>

#include <stdlib.h>

int main()

{

    FILE *fp;

    char fname[50];

    clrscr();

    /* read name of the file to be opened */

    printf(“Enter input file name: “);

    gets(fname);

    /* open the specified file */

    fp = fopen(fname, “rt”);

    if (fp == NULL) {

        printf(“Error: Unable to open file %s\n”, fname);

        exit(1);

       }

    /* perform input operations on given file */

    fclose(fp) ;   /* close the file */

    return 0;

}

The variable fp is a pointer to a file structure and the character array fname is used to store the file name. The program first reads the name of the file to be opened using the gets function.

The fopen function is then used to open the specified file in read mode and the return value (a file pointer) is assigned to variable fp.If the file opening operation was unsuccessful ( fp is NULL), the program displays an error message and exits with error code 1. Otherwise, program execution continues and we can perform the desired input operations on the specified file using the file pointer fp. Finally, when the input operations are over, the file is closed using fclose. Note that we can rewrite the code for opening a file in a concise way by calling fopen from within the condition in the if statement as shown below.

if ((fp = fopen(“STUD.DAT”, “rt”)) == NULL) {

printf(“Error: Unable to open file STUD.DAT\n”);

exit(1);

Note that since the assignment operator has lower precedence than the equality operator, the fopen function call is enclosed within a pair of parentheses. Thus, the value returned by the fopen function is first assigned to the variable fp and then compared with NULL. Without the parentheses, the value returned by fopen will first be compared with NULL and then the outcome of this comparison will be assigned to variable fp, which is incorrect.

Example of Function to open a file

In above Example, observe that the code to read a file name from the keyboard and open the file spans several lines. Since almost every program involving file processing will require one or more files to be opened, it is a good idea to write a utility functions to perform this operation. Such a function will also enable us to keep the code in subsequent example programs concise. We will generalize this function to accept the file name from either the calling function or the keyboard.

The fileopen function given below has three parameters: fname, mode and msg. The parameter fname usually specifies the name of the file to be opened. However, if message string msg is not a NULL string, the function displays msg and reads a file name from the keyboard. The specified file is then opened in the given mode using fopen. If the file is opened successfully, the function returns the file pointer; otherwise, it displays an error message and exits the program.

/* open a file in specified mode */

FILE *fileopen(char *fname, const char *mode, const char *msg)

{

     FILE *fp;

     /* if msg is not a NULL string, read file name from keyboard */

     if (strlen (msg) > 0) {

     printf(“%s”, msg);

     scanf(“%s”, fname);

}

/* open the file */

if ((fp = fopen(fname, mode)) ==NULL) {

     printf(“Error: Unable to open file %s\n”, fname);

     exit(1);

}

     return fp;

}

To open a text file called marks .dat in read mode, we can call this function as shown below.

fp = fileopen(“marks.dat”, “rt”,””);

On the other hand, to read the file name from the keyboard and open that file as a text file in read mode, we can call this function as follows:

char fname[50];

fp = fileopen(fname, “rt”, “Enter input file name: “);

Note that we should copy this function in each program that uses it. This can be tedious, as we may have to add the prototype of this function at the beginning of the program. Alternatively, we can save this function in a text file, say fileopen. c, along with the required #include statements given below.

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

Now we can include this file in each program as shown below.

#include “fileopen.c”

Observe that the filename fileopen. c has been enclosed in double quotes, the convention to be followed for including user-defined files in a C program. We will use this approach in subsequent programs that require this function.

You’ll also like:

  1. Write A C++ Program To Add, Subtract And Multiply Two Numbers By Using The Function Within Function Concept (Nesting Of Function).
  2. Write A C++ Program To Find The Sum Of: 1! /5+ 2! /4+ 3! /3+ 4! /2+ 5! /1 Without Using Function (Except Main Function). Where! Symbol Indicates Factorial Of Any Number.
  3. What is Function Declarations or Function Prototype?
  4. Function freopen () in C
  5. Function ungetc() in C
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

C Programming

C Programming Tutorials

  • C - History
  • C - Anatomy
  • C - Constants
  • C - Identifiers
  • C - Data Types
  • C - Libraries File
  • C - Header Files
  • C - Basic Language
  • C - Data Types Sizes
  • C - Header Files Importance
  • C - Escape Sequences
  • C - Main() Purpose
  • C - Program Procedure
  • C - Control Statements
  • C - Enumeration Constant
  • C - Add numbers
  • C - Return Statement
  • C - Avoid Goto
  • C - Command Line Arguments
  • C - Switch Case
  • C - Switch Case Limitations
  • C - getchar() and putchar()
  • C - Iteration Statements
  • C - Pass by Value and Reference
  • C - Structures and Unions
  • C - Structure
  • C - Dynamic Memory
  • C - Fgets and Fputs Functions
  • C - Gets() and Puts() Functions
  • C - Armstrong Number
  • C - Storage Classes
  • C - Fibonacci Series
  • C - Precision Setting
  • C - const Parameters

C - Variable & It's Type

  • C - Variables
  • C - Variable Lifetime
  • C - Static Variable
  • C - Register Variable
  • C - Global Variables
  • C - Auto Variables
  • C - Local Variables

C - Operator & Expressions

  • C - Operator
  • C - Boolean Operators
  • C - Bitwise Operator
  • C - Arithmetic Operators
  • C - Modulus Operator
  • C - Ternary Operator
  • C - Expressions
  • C - Arithmetic Expressions

C - Array

  • C - Arrays
  • C - Array Types
  • C - Array Characteristics
  • C - Static Arrays
  • C - Global Arrays
  • C - 3D Arrays
  • C - Dynamic Arrays
  • C - Pointer to 3D Arrays
  • C - Array Elements Hold
  • C - Arrays as Function Parameters
  • C - Accessing Matrix Elements
  • C - File Handling
  • C - Matrix Multiplication
  • C - Dynamic Memory Allocation

C - Searching & Sorting

  • C - Data Structures
  • C - Linear Search
  • C - Bubble Sort
  • C - Merge Sort
  • C - Linked List
  • C - Insertion Sort
  • C - Binary Search
  • C - Selection Sort
  • C - Quick Sort

C - Functions

  • C - Functions
  • C - Functions Advantages
  • C - Void Functions
  • C - Function Call
  • C - Default Return Value
  • C - String functions

C - Pointer

  • C - Pointers
  • C - Type Casting Of Pointers
  • C - Pointer Advantages
  • C - Pointers Initialization
  • C - Vectors and Pointers

C - Differences

  • C - C Vs C++
  • C - Formal Args. Vs Actual Args.
  • C - Keywords Vs Identifiers
  • C - Strings Vs Character Arrays
  • C - Address Vs Dereference Operator
  • C - Goto Vs longjmp
  • C - Declaring Vs Defining Variable
  • C - String Vs Array
  • C - Call by Value Vs Reference
  • C - Structure Vs Union
  • C - For Vs While loops
  • C - Compiler Vs Interpreter

C - Programs

  • C Program Standard Deviation
  • C Program Calculate Tax
  • C Program Sum Series
  • C Program Merge Arrays
  • C Program Euclid’s Algorithm
  • C Program Print Weekdays
  • C Program Sum of Digits
  • C Program Print a list
  • C Program Print Pythagorean
  • C Program Quiz program
  • C Program Display Table
  • C Program Print Comma-Separated
  • C Program Prints Prime Numbers
  • C Program for Print Integer
  • C Program Count Number
  • C Program Print Color Name
  • C Program Print Odd Numbers
  • C Program Calculate area
  • C Program for a Menu
  • C Program Add Two Vectors
  • C Program Array Addresses
  • C Program Division by Zero Error
  • C Program Compare two Dates
  • C Program Tower of Hanoi
  • C Program return 3 Numbers
  • C Program for Prime Numbers
  • C Program for Factorial
  • C Program for Palindrome

Other Links

  • C Programming - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW