9.5: The Three-Step Process for Advanced File I/O

Fundamentals of MATLAB Programming · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC-SA, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    9.5: The Three-Step Process for Advanced File I/O

    When we use more advanced file I/O functions, the process usually has three steps:

    1. Open the file.

    2. Read from the file, write to the file, or append to the file.

    3. Close the file.

    This may feel like extra work at first, but it gives us much more control. It also helps MATLAB communicate with the operating system safely.

    Opening a File with fopen

    The function fopen is used to open a file. The basic format is:

    fid = fopen('filename', 'permission')

    The output fid stands for file identifier. You can think of it as a number MATLAB uses to refer to the open file.

    If the file opens successfully, fopen returns an integer value. If the file does not open successfully, fopen returns -1.

    Permission string

    Meaning

    What happens

    'r'

    Read

    Open an existing file for reading. This is the default.

    'w'

    Write

    Create a new file or overwrite an existing file.

    'a'

    Append

    Add new information to the end of an existing file.

    Because files do not always open successfully, it is good practice to check the value of fid before trying to use the file.

    fid = fopen('samp.dat');
    
    if fid == -1
        disp('File open was not successful')
    else
        % Carry on and use the file!
    end
    Note

    Always check whether the file opened successfully before trying to read from it or write to it. This makes your program much easier to debug.

    Closing a File with fclose

    After MATLAB is finished using a file, the file should be closed using fclose.

    closeresult = fclose(fid);

    fclose returns 0 if the file closed successfully and -1 otherwise. It is also possible to close all open files using:

    fclose('all')

    Closing files is important because it releases the file for other programs and makes sure any written data is properly saved.


    This page titled 9.5: The Three-Step Process for Advanced File I/O was last modified on Tue, 30 Jun 2026 02:12:02 GMT and is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Zara Noroozi.