RunMat
  • Pricing
RunMat
GitHub
GitHub
DownloadSign InTry in Browser
DesktopRuntimeServer
RunMat

Run math blazing fast

GitHubX (Twitter)LinkedIn

Company

  • About
  • Pricing
  • Contact
  • License
  • Privacy

Learn

  • Docs
  • Blog
  • Benchmarks
  • RunMat vs MATLAB Online

Get product updates and release notes from the RunMat team.

© 2026 Dystr · Made withfor the scientific community.

RunMat™ is a registered trademark of Dystr, Inc. MATLAB® is a registered trademark of The MathWorks, Inc. RunMat is not affiliated with, endorsed by, or sponsored by The MathWorks, Inc.

/
See all docs
Builtin Reference
    • fclose
    • feof
    • fgetl
    • fgets
    • fileread
    • filewrite
    • fopen
    • fprintf
    • fread
    • frewind
    • fwrite
    • readlines
    • writelines

fgets — Read the next line including newline characters in MATLAB and RunMat.

fgets(fid) reads the next line from a text file and preserves trailing newline characters in the returned text. The optional nchar limit caps the number of characters returned.

Syntax

tline = fgets(fid)
tline = fgets(fid, nchar)
[tline, terminators] = fgets(fid, ...)

Inputs

NameTypeRequiredDefaultDescription
fidNumericScalarYes—File identifier opened by fopen.
ncharNumericScalarNo—Maximum number of characters to read.

Returns

NameTypeDescription
tlineAnyNext line including terminators, or -1 at end-of-file.
terminatorsNumericArrayNumeric row vector of terminator byte values.

Returned values from fgets depend on how many outputs the caller requests.

Errors

IdentifierWhenMessage
RunMat:fgets:InvalidInputInput argument count or scalar constraints are invalid.fgets: invalid input arguments
RunMat:fgets:InvalidIdentifierIdentifier does not refer to an open readable file.fgets: invalid file identifier. Use fopen to generate a valid file ID.
RunMat:fgets:IoFailureFile read or decode operation failed.fgets: file I/O failed
—Internal control-flow conversion failed.fgets: internal error

How fgets works

  • tline = fgets(fid) reads from the current position to the next newline (including the newline) or to end-of-file when no terminator is found. The result is a character row vector with MATLAB's column-major semantics.
  • tline = fgets(fid, nchar) limits the read to at most nchar characters. The call stops early if a newline is encountered before the limit, and content beyond the limit remains unread for the next call.
  • [tline, ltout] = fgets(___) additionally reports the line terminator integer code or codes, if any.
  • When no characters can be read because the file position is already at end-of-file, tline returns the double sentinel -1.
  • Lines are decoded using the text encoding recorded by fopen.

Does RunMat run fgets on the GPU?

fgets is a host-only operation. Provider-resident arguments are gated RunMat extensions; when enabled, RunMat gathers them before reading and returns regular host values.

Examples

Read the first line of a file

fname = tempname;
fid = fopen(fname, 'w');
fprintf(fid, 'RunMat\nSecond line\n');
fclose(fid);

fid = fopen(fname, 'r');
line = fgets(fid);
fclose(fid);
delete(fname);

double(line)

Expected output:

ans =
    82   117   110    77    97   116    10

Limit the number of characters returned

fname = tempname;
fid = fopen(fname, 'w');
fprintf(fid, 'Example line\n');
fclose(fid);

fid = fopen(fname, 'r');
snippet = fgets(fid, 5);
fclose(fid);
delete(fname);

snippet
double(snippet)

Expected output:

snippet =
    'Examp'
ans =
    69   120    97   109   112

Retrieve a line terminator separately

fname = tempname;
fid = fopen(fname, 'w');
fprintf(fid, 'Line\n');
fclose(fid);

fid = fopen(fname, 'r');
[line, ltout] = fgets(fid);
fclose(fid);
delete(fname);

line
ltout

Expected output:

line =
    'Line
     '
ltout =
    10

Handle lines without a trailing newline

fname = tempname;
fid = fopen(fname, 'w');
fprintf(fid, 'last line');
fclose(fid);

fid = fopen(fname, 'r');
line1 = fgets(fid);
line2 = fgets(fid);
fclose(fid);
delete(fname);

line1
line2

Expected output:

line1 =
    'last line'
line2 =
    -1

Detect end of file using the return value

fname = tempname;
fid = fopen(fname, 'w');
fprintf(fid, 'one\n');
fprintf(fid, 'two\n');
fclose(fid);

fid = fopen(fname, 'r');
tline = fgets(fid);
while tline ~= -1
    fprintf('> %s', tline);
    tline = fgets(fid);
end
fclose(fid);
delete(fname)

Expected output:

> one
> two

Read Latin-1 encoded text

fname = tempname;
fid = fopen(fname, 'w', 'n', 'latin1');
fprintf(fid, 'Español\n');
fclose(fid);

fid = fopen(fname, 'r', 'n', 'latin1');
line = fgets(fid);
fclose(fid);
delete(fname);

text = line(1:end-1);
codes = double(text);

text
codes

Expected output:

text =
    'Español'
codes =
    69   115   112    97   241   111   108

Using fgets with coding agents

Open a RunMat example with live inputs, then ask the agent to explain how fgets changes the result.

Run a small fgets example, explain the result, then change one input and compare the output.

FAQ

What does fgets return at end-of-file?⌄

When no characters can be read because the file position indicator is at end-of-file, fgets returns the double value -1 for tline.

Does fgets strip newline characters?⌄

No. Unlike fgetl, fgets keeps any newline bytes in the returned character vector so you can distinguish empty lines from lines that end in a newline.

How do I interpret the second output ltout?⌄

ltout reports the integer code or codes for the terminator that ended the line. The precise container behavior for every multi-character and no-terminator boundary is not claimed here.

What happens if I specify an nchar limit?⌄

RunMat reads at most nchar characters. If a newline is encountered first, the read stops there; otherwise content beyond the limit remains unread for the next call.

Which encodings are supported?⌄

fgets decodes the line using the encoding recorded by fopen.

How does fgets differ from fgetl?⌄

fgetl removes newline characters, while fgets keeps them. Use fgetl when you want newline-free strings and fgets when you need to preserve the exact bytes that appear in the file.

Can I call fgets on files opened for writing only?⌄

No. The file must be opened with read permission (for example 'r', 'r+', or 'w+'). Calling fgets on a write-only identifier raises an error.

Can fgets read from standard input with fgets(0)?⌄

No. MATLAB disallows fgets(0) for the interactive stdin stream and RunMat follows the same convention. Use input('prompt: ', 's') for interactive prompts, or read a real file identifier returned by fopen.

How do I read a whole file line-by-line with fgets?⌄

Open the file, loop while the return value is not -1, and close the handle when you are done. Pair the call with feof or compare against -1 directly:

fid = fopen('data.txt', 'r');
while ~feof(fid)
    line = fgets(fid);
    if line == -1, break; end
    fprintf('%s', line);
end
fclose(fid);
How do I reliably detect end-of-file with fgets?⌄

Test ischar(line) or compare the return value to -1. A successful line read returns a character vector, while an EOF read with no characters available returns the double sentinel -1.

Related Io functions

Filetext

fclose · feof · fgetl · fileread · filewrite · fopen · fprintf · fread · frewind · fwrite · readlines · writelines

Net

accept · read · readline · tcpclient · tcpserver · write

Repl Fs

addpath · cd · copyfile · delete · dir · exist · fileattrib · fileparts · fullfile · genpath · getenv · getpref · isenv · isfile · isfolder · ispref · ls · matlabroot · memmapfile · mkdir · movefile · open · opentoline · path · pathsep · pcode · pwd · readstruct · rehash · restoredefaultpath · rmdir · rmpath · run · savepath · setenv · setpref · system · tempdir · tempname · uigetdir · uigetfile · uiputfile · unsetenv · userpath · what · winqueryreg · xmlread · xmlwrite

Tabular

arrayDatastore · csvread · csvwrite · detectImportOptions · dlmread · dlmwrite · fileDatastore · parquetDatastore · parquetinfo · parquetread · readcell · readmatrix · readtable · readtimetable · spreadsheetImportOptions · writecell · writematrix · writetable · writetimetable · xlsread · xlswrite

Audio

audioinfo · audioread

Io

clc · diary · disp · display · format · input

Archive

gunzip · gzip · unzip

Hdf5

h5disp · h5info · h5read · h5write · h5writeatt · hdf5info · hdf5read · hdf5write

Import

importdata · textscan

Json

jsondecode · jsonencode

Mat

load · matfile · save

Http

sendmail · urldecode · urlencode · weboptions · webread · websave · webwrite

Open-source implementation

Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how fgets is executed, line by line, in Rust.

  • View the source for fgets in Rust on GitHub
  • Learn how the RunMat runtime works
  • Found a bug? Open an issue with a minimal reproduction.

About RunMat

RunMat is an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 license.

  • RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
  • Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.

Getting started · Benchmarks · Pricing

Download RunMat

Download RunMat for full performance, or use RunMat in your browser for zero setup.

Download RunMatOpen Sandbox
On this page
  • Syntax
  • Inputs
  • Returns
  • Errors
  • How fgets works
  • Does RunMat run fgets on the GPU?
  • Examples
  • Read the first line of a file
  • Limit the number of characters returned
  • Retrieve a line terminator separately
  • Handle lines without a trailing newline
  • Detect end of file using the return value
  • Read Latin-1 encoded text
  • Using fgets with coding agents
  • FAQ
  • Related Io functions
  • Filetext
  • Net
  • Repl Fs
  • Tabular
  • Audio
  • Io
  • Archive
  • Hdf5
  • Import
  • Json
  • Mat
  • Http
  • Open-source implementation
  • About RunMat