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
| 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 mostncharcharacters. 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,
tlinereturns 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 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 =
'Examp'
ans =
69 120 97 109 112Retrieve 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
ltoutExpected output:
line =
'Line
'
ltout =
10Handle 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
line2Expected output:
line1 =
'last line'
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 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
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
Import
Json
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.