fgets — Read a line while retaining its newline characters.
fgets(fid) reads from the shared file cursor through the next line terminator, including the terminator. fgets(fid, nchar) limits the read, and a second output reports the terminator byte values. EOF before any character returns double -1.
Syntax
tline = fgets(fid)
tline = fgets(fid, nchar)
[tline, terminators] = fgets(fid, ...)Inputs
fid- Type
NumericScalar- Required
- Yes
- Description
- File identifier opened by fopen.
nchar- Type
NumericScalar- Required
- No
- Description
- Maximum number of characters to read.
Returns
tline- Type
Any- Description
- Next line including terminators, or -1 at end-of-file.
terminators- Type
NumericArray- Description
- Numeric row vector of terminator byte values.
Returned values from fgets depend on how many outputs the caller requests.
Errors
RunMat:fgets:InvalidInput- When
- Input argument count or scalar constraints are invalid.
- Message
fgets: invalid input arguments
RunMat:fgets:InvalidIdentifier- When
- Identifier does not refer to an open readable file.
- Message
fgets: invalid file identifier. Use fopen to generate a valid file ID.
RunMat:fgets:IoFailure- When
- File read or decode operation failed.
- Message
fgets: file I/O failed
- When
- Internal control-flow conversion failed.
- Message
fgets: internal error
Lines, limits, and EOF
A successful read returns a host character row retaining CR, LF, CRLF, or LFCR terminators. The optional second output is a numeric row of their byte codes, empty when no terminator ended the line. At EOF before any character both outputs are double -1. A final unterminated line is still returned once.
nchar must be a nonnegative integer-valued scalar. The current reader applies this limit to input bytes before decoding, so a limit that splits a multibyte character can raise a decode error. Later bytes stay available for the next call; zero returns an empty character row. The compatible forms use scalar double identifiers and limits. Typed integer, Single, and resident scalar variants each have separate RunMat extension gates and exact integer bounds.
The identifier must be open for reading. Standard stream identifier 0 is not supported; use input for interactive prompts. The file's fopen encoding controls decoding. fgetl differs by removing the terminator. Check ischar(line) to distinguish an empty character row from numeric EOF -1.
Placement and filesystem
The file handle, cursor, and returned text remain host-owned. There is no GPU kernel or fusion path. Admitted resident scalar controls are gathered from their exact provider owner after compatibility checks; the caller retains the original allocation.
The installed filesystem provider supplies the file. Browser use requires an installed file service with appropriate permissions; the runnable examples use isolated fixtures rather than ambient login or a public path.
Examples
Read the first line including newline
fid = fopen('lines.txt', 'r');
assert(fid >= 3);
line = fgets(fid);
status = fclose(fid);
lineLimit the number of returned characters
fid = fopen('limited.txt', 'r');
assert(fid >= 3);
snippet = fgets(fid, 5);
next = fgets(fid);
status = fclose(fid);
snippet
nextExpected output:
snippet = ExampInspect newline bytes separately
fid = fopen('terminator.txt', 'r');
assert(fid >= 3);
[line, ltout] = fgets(fid);
status = fclose(fid);
line
ltoutRead the final line without newline
fid = fopen('final.txt', 'r');
assert(fid >= 3);
first = fgets(fid);
second = fgets(fid);
status = fclose(fid);
first
secondRead lines until the numeric EOF sentinel
fid = fopen('two.txt', 'r');
assert(fid >= 3);
count = 0;
line = fgets(fid);
while ischar(line)
count = count + 1;
if count == 1
assert(strcmp(line, sprintf('one\n')));
else
assert(count == 2);
assert(strcmp(line, sprintf('two\n')));
end
fprintf('> %s', line);
line = fgets(fid);
end
status = fclose(fid);Expected output:
> one
> twoDecode text with the recorded Latin-1 encoding
fid = fopen('latin1.txt', 'r', 'n', 'latin1');
assert(fid >= 3);
line = fgets(fid);
status = fclose(fid);
lineUsing 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 is returned at EOF?⌄
Double -1 when no character can be read; successful lines are character rows, including an empty row for a zero-character limit.
Are newline characters stripped?⌄
No. fgets retains them; fgetl removes them.
What is the second output?⌄
A numeric row of terminating byte codes, empty if the read stopped without a terminator, or double -1 at EOF before any character.
What does nchar do?⌄
The current reader limits input bytes before text decoding; content beyond the limit remains unread, and splitting a multibyte character can fail decoding.
Which encoding applies?⌄
The encoding recorded by fopen is used to decode the line.
Can it read a write-only file or stdin?⌄
No. The handle must have read permission; interactive standard input identifier 0 is not supported here.
How do I loop reliably?⌄
Read while ischar(line) and close the identifier afterward; EOF is the numeric -1 sentinel.
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 · filesep · fullfile · genpath · getenv · getpref · isenv · isfile · isfolder · ispref · ls · matlabroot · memmapfile · memmapfile.subsasgn · memmapfile.subsref · 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 · getvaropts · parquetDatastore · parquetinfo · parquetread · readcell · readmatrix · readtable · readtimetable · setvaropts · setvartype · spreadsheetImportOptions · writecell · writematrix · writetable · writetimetable · xlsread · xlswrite
Data
commit · data.copy · data.create · data.delete · data.exists · data.export · data.import · data.inspect · data.list · data.move · data.open · DataArray.chunk_shape · DataArray.codec · DataArray.dtype · DataArray.fill · DataArray.name · DataArray.rank · DataArray.read · DataArray.resize · DataArray.shape · DataArray.write · Dataset.array · Dataset.arrays · Dataset.attrs · Dataset.begin · Dataset.get_attr · Dataset.has_array · Dataset.id · Dataset.path · Dataset.refresh · Dataset.set_attr · Dataset.set_attrs · Dataset.snapshot · Dataset.version · DataTransaction.abort · DataTransaction.commit · DataTransaction.create_array · DataTransaction.delete_array · DataTransaction.fill · DataTransaction.id · DataTransaction.resize · DataTransaction.set_attr · DataTransaction.set_attrs · DataTransaction.status · DataTransaction.write
Import
Json
Source you can read
Every RunMat function's source is public. 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 a runtime that executes MATLAB-syntax code fast on any GPU. The runtime is free for individuals, including freelancers; students and faculty at an academic institution, for teaching or research there; contributors to an open-source project, for work on that project; organizations with 250 or fewer people and US$10M or less in annual revenue; and anyone, for non-production use. See runmat.com/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.