fclose - what is the purpose?

Hi,
Why do i need to use fclose when opening a file? what happens if the file remains open?
I'm trying to understand the logic behind it, and could not understand from the function help and description.
thank,

 Accepted Answer

Stephen23
Stephen23 on 4 Feb 2019
Edited: Stephen23 on 4 Feb 2019
Short Answer:
Files need to be opened and closed for reasons that depend on how OS's work, not because of how MATLAB works. Files saved on a drive are not instantly accessible at any moment: to read or write to a file, the OS has to create a handle to it: creating a file handle has overhead and requires system resources. If you do not close files, then these file handles will accumulate, waste system resources, and eventually can crash any application trying to access files (e.g. MATLAB):
When you fclose the file then those system resources are released.
Longer Answer:
This really has nothing to do with MATLAB. Use the internet. When I searched for "why files open close" using [a major internet search engine] it returned 2500 million results. The first ones that I looked at gave good overviews, and some gave more detailed explanations
etc. etc.
Be prepared for learning a lot about how OS's work!

2 Comments

Within the contest of matlab, we can summarise it as follow:
  • if you open a file in write mode (includes append mode), nobody else can read or write to the file until you've closed it.
  • if you open a file in read mode, nobody else can write to the file until you've closed it. It can still be open in read-only mode by others
  • If a file is open, it cannot be moved or deleted.
great, i will check it out. thank you both.

Sign in to comment.

More Answers (0)

Categories

Find more on Data Import and Analysis in Help Center and File Exchange

Products

Release

R2018b

Tags

Asked:

on 4 Feb 2019

Commented:

on 4 Feb 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!