9.7: Reading One Line at a Time with fgetl

Fundamentals of MATLAB Programming · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    Read aloud

    How

    Speed: 1×
    Light up
    Highlight

    Symbols: Mulberry Symbols, © 2018–2026 Steve Lee, CC BY-SA 4.0 (licence, the set), the site's own copies.

    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.7: Reading One Line at a Time with fgetl

    Sometimes we do not want to read the entire file all at once. Instead, we may want to read one line, process that line, then move to the next line. The function fgetl is useful for this.

    fgetl reads the next line of a file and removes the newline character at the end of the line. The format is:

    aline = fgetl(fid)

    If there is another line to read, fgetl returns that line as a character vector. If MATLAB has reached the end of the file, fgetl returns -1.

    Basic fgetl Pattern

    fid = fopen('example.txt');

    if fid == -1
    disp('File open was not successful')
    else
    while true
    aline = fgetl(fid);

    if aline == -1
    break
    end

    disp(aline)
    end

    fclose(fid);
    end

    The phrase while true creates a loop that keeps going until we explicitly stop it with break. In this case, the loop stops when fgetl returns -1, which means there are no more lines to read.

    Example 9.4: Formatting Phone Numbers

    Example \(\PageIndex{1}\)

    Formatting Phone Numbers

    Suppose we have a file named phones.dat containing phone numbers in this form:

    6012425932
    6178987654
    8034562468
    9492150918

    We want MATLAB to display the phone numbers with hyphens, like this:

    601-242-5932

    The following script reads the file one line at a time, checks that each number has 10 digits, and then prints the formatted phone number.

    fid = fopen('phones.dat');
    
    if fid == -1
        disp('File open was not successful')
    else
        while true
            phone = fgetl(fid);
    
            if phone == -1
                break
            end
    
            if length(phone) == 10 && all(isstrprop(phone, 'digit'))
                fprintf('%s-%s-%s\n', phone(1:3), phone(4:6), phone(7:10));
            else
                fprintf('Invalid phone number: %s\n', phone);
            end
        end
    
        fclose(fid);
    end

    This is a good example of why line-by-line reading can be useful. We can check and process each line individually.


    This page titled 9.7: Reading One Line at a Time with fgetl 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.