14.2.3 Line-Oriented Input

To read from a file it must be opened for reading using fopen. Then a line can be read from the file using fgetl as the following code illustrates

fid = fopen ("free.txt");
txt = fgetl (fid)
     -| Free Software is needed for Free Science
fclose (fid);

This of course assumes that the file ‘free.txt’ exists and contains the line ‘Free Software is needed for Free Science’.

str = fgetl (fid)
str = fgetl (fid, len)

Read characters from a file, stopping after a newline, or EOF, or len characters have been read.

The characters read, excluding the possible trailing newline, are returned as a string.

If len is omitted, fgetl reads until the next newline character.

If there are no more characters to read, fgetl returns -1.

To read a line and return the terminating newline see fgets.

See also: fgets, fscanf, fread, fopen.

str = fgets (fid)
str = fgets (fid, len)

Read characters from a file, stopping after a newline, or EOF, or len characters have been read.

The characters read, including the possible trailing newline, are returned as a string.

If len is omitted, fgets reads until the next newline character.

If there are no more characters to read, fgets returns -1.

To read a line and discard the terminating newline see fgetl.

See also: fputs, fgetl, fscanf, fread, fopen.

nlines = fskipl (fid)
nlines = fskipl (fid, count)
nlines = fskipl (fid, Inf)

Read and skip count lines from the file specified by the file descriptor fid.

fskipl discards characters until an end-of-line is encountered exactly count-times, or until the end-of-file marker is found.

If count is omitted, it defaults to 1. count may also be Inf, in which case lines are skipped until the end of the file. This form is suitable for counting the number of lines in a file.

Returns the number of lines skipped (end-of-line sequences encountered).

See also: fgetl, fgets, fscanf, fopen.

© 1996–2020 John W. Eaton
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.
https://octave.org/doc/v5.2.0/Line_002dOriented-Input.html