fgets — Read the next line including newline characters in MATLAB and RunMat.
fgets(fid) reads the next line from a text file and preserves any trailing newline characters in the returned text. Optional length limits, terminator behavior, and EOF handling follow MATLAB semantics.
Syntax
tline = fgets(fid)
tline = fgets(fid, nchar)
[tline, terminators] = fgets(fid, ...)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
fid | NumericScalar | Yes | — | File identifier opened by fopen. |
nchar | NumericScalar | No | — | Maximum number of characters to read. |
Returns
| Name | Type | Description |
|---|---|---|
tline | Any | Next line including terminators, or -1 at end-of-file. |
terminators | NumericArray | Numeric row vector of terminator byte values. |
Returned values from fgets depend on how many outputs the caller requests.
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:fgets:InvalidInput | Input argument count or scalar constraints are invalid. | fgets: invalid input arguments |
RunMat:fgets:InvalidIdentifier | Identifier does not refer to an open readable file. | fgets: invalid file identifier. Use fopen to generate a valid file ID. |
RunMat:fgets:IoFailure | File 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 mostnchar-1characters (withncharrounded toward zero), matching MATLAB. The call stops early if a newline is encountered before the limit. When the newline appears beyond the limit, the delimiter is left unread for the next call.[tline, ltout] = fgets(___)additionally returns the line terminators as a row vector of doubles. For Windows newlines (\r\n) the second output is[13 10], for Unix newlines (\n) it is10, and it is empty when the line has no terminator.- When the file is empty or the file position indicator is already at end-of-file,
tline(andltout, if requested) return-1. - Lines are decoded using the text encoding recorded by
fopen. UTF-8, US-ASCII, ISO-8859-1 (latin1), Windows-1252, Shift_JIS, and binary mode are recognised without additional user work.
Does RunMat run fgets on the GPU?
fgets is a host-only operation. File identifiers live in the host registry created by fopen, so arguments that arrive as GPU-resident scalars are gathered back to the CPU before the read occurs. The returned line and optional terminator vector are regular host values; no GPU residency is tracked.
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 10Limit 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 =
'Exam'
ans =
69 120 97 109Retrieve line terminators separately
fname = tempname;
fid = fopen(fname, 'w');
fprintf(fid, 'Windows line\r\n');
fclose(fid);
fid = fopen(fname, 'r');
[line, ltout] = fgets(fid);
fclose(fid);
delete(fname);
content = line(1:end-numel(ltout));
terminators = double(ltout);
content
terminatorsExpected output:
content =
'Windows line'
terminators =
13 10Handle lines without a trailing newline
fname = tempname;
fid = fopen(fname, 'w');
fprintf(fid, 'last line');
fclose(fid);
fid = fopen(fname, 'r');
[line1, lt1] = fgets(fid);
line2 = fgets(fid);
fclose(fid);
delete(fname);
line1
lt1
line2Expected output:
line1 =
'last line'
lt1 =
[]
line2 =
-1Detect 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
> twoRead 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
codesExpected output:
text =
'Español'
codes =
69 115 112 97 241 111 108Using 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 numeric value -1. If you request two outputs, ltout is also -1 in this case.
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 contains the numeric codes for the terminators that ended the line. Use char(ltout) or double(ltout) to inspect them. On Windows you typically see [13 10], on Unix-like platforms 10, [] when the line has no terminator, and -1 when end-of-file is reached.
What happens if I specify an nchar limit?⌄
RunMat reads at most nchar-1 characters (MATLAB-compatible). If the newline characters appear before reaching the limit, they are included in the output. If the limit is reached first, the newline remains unread and ltout is empty.
Which encodings are supported?⌄
fgets honours the encoding recorded by fopen. UTF-8, US-ASCII, Latin-1 (ISO-8859-1), Windows-1252, Shift_JIS, and binary mode are recognised. On most Unix-like systems the system encoding resolves to UTF-8; on Windows it defaults to Windows-1252.
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?⌄
Compare the return value to -1 (if line == -1) or query feof(fid) before the next read. Do not use ischar(line), because MATLAB's implicit numeric-to-char rules can report true for the sentinel value on some inputs.
Related Io functions
Repl Fs
addpath · cd · copyfile · delete · dir · exist · fullfile · genpath · getenv · ls · mkdir · movefile · path · pwd · rmdir · rmpath · run · savepath · setenv · tempdir · tempname · uigetfile · uiputfile
Tabular
csvread · csvwrite · detectImportOptions · dlmread · dlmwrite · readmatrix · spreadsheetImportOptions · writecell · writematrix · xlsread
Import
Json
Archive
Http
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.