fopen — Open, query, or list host file identifiers.
fopen opens a file and returns a double file identifier used by the other file-I/O functions. It also queries an existing identifier, and RunMat extension mode can list open files.
Syntax
fid = fopen(filename)
fid = fopen(filename, permission)
fid = fopen(filename, permission, machinefmt)
fid = fopen(filename, permission, machinefmt, encoding)
[fid, msg] = fopen(filename, ...)
[fid, msg, machinefmt, encoding] = fopen(filename, ...)All supported fopen forms
fid = fopen(filename)
fid = fopen(filename, permission)
fid = fopen(filename, permission, machinefmt)
fid = fopen(filename, permission, machinefmt, encoding)
[fid, msg] = fopen(filename, ...)
[fid, msg, machinefmt, encoding] = fopen(filename, ...)
filename = fopen(fid)
[filename, permission, machinefmt, encoding] = fopen(fid)
fids = fopen("all")
fids = fopen("all", machinefmt)
[fids, names, machinefmts, encodings] = fopen("all")
[fids, names, machinefmts, encodings] = fopen("all", machinefmt)Inputs
filename- Type
Any- Required
- Yes
- Description
- Path to file to open.
permission- Type
StringScalar- Required
- No
- Default
"r"- Description
- Permission string such as 'r', 'w', 'a', optionally with '+'/'b'/'t'.
machinefmt- Type
StringScalar- Required
- No
- Default
"native"- Description
- Machine-format label.
encoding- Type
StringScalar- Required
- No
- Default
"UTF-8"- Description
- Encoding label.
fid- Type
NumericScalar- Required
- Yes
- Description
- Numeric file identifier.
selector- Type
StringScalar- Required
- Yes
- Default
"all"- Description
- Literal selector 'all'.
machinefmt- Type
StringScalar- Required
- No
- Description
- Machine-format filter for listed handles.
Returns
fid- Type
NumericScalar- Description
- File identifier on success, or -1 on failure.
msg- Type
StringScalar- Description
- Open failure message string (empty on success).
machinefmt- Type
StringScalar- Description
- Resolved machine-format label for the opened stream.
encoding- Type
StringScalar- Description
- Resolved encoding label for the opened stream.
filename- Type
StringScalar- Description
- Filename associated with queried file identifier.
permission- Type
StringScalar- Description
- Canonical fopen permission string.
machinefmt- Type
StringScalar- Description
- Machine-format label of queried stream.
encoding- Type
StringScalar- Description
- Encoding label of queried stream.
fids- Type
NumericArray- Description
- Column vector of open user file identifiers.
names- Type
Any- Description
- Cell column of display names.
machinefmts- Type
Any- Description
- Cell column of machine-format labels.
encodings- Type
Any- Description
- Cell column of encoding labels.
Returned values from fopen depend on how many outputs the caller requests.
Errors
RunMat:fopen:InvalidInput- When
- Argument count or argument shape/type is invalid.
- Message
fopen: invalid input arguments
RunMat:fopen:InvalidPermission- When
- Permission string is invalid or unsupported.
- Message
fopen: invalid permission string
RunMat:fopen:InvalidMachineFormat- When
- Machine-format argument is invalid or unsupported.
- Message
fopen: invalid machine format
Open, query, and list
fid = fopen(filename) opens an existing file for reading. A failed open returns double -1; [fid, message] adds the operating-system error text. On success the message is empty. The third and fourth open outputs report the resolved machine format and encoding, or empty character values on failure.
Permissions include r, w, a, r+, w+, and a+, optionally with b or t. Write truncates, append appends, and + allows both reading and writing. Binary permission defaults to the pseudo-encoding binary; text mode defaults to UTF-8. The machine format records native, ieee-le, or ieee-be for later binary I/O. Explicit encoding is retained in the registry.
[filename, permission, machinefmt, encoding] = fopen(fid) queries a registered identifier. An unregistered identifier returns empty character metadata. The compatible query identifier is a finite integer-valued double; typed integer, single, and resident query identifiers are independently gated RunMat extensions and exact integer range is checked before registry access.
No-argument and 'all' listing forms are gated RunMat extensions. [ids, names, formats, encodings] = fopen('all') reports current standard streams and open files; fopen('all', machinefmt) filters by recorded format. MATLAB-compatible modes reject these legacy selectors.
The runtime pads requested outputs beyond the four named slots with double zeros. This legacy requested-output behavior is distinct from the documented four named values.
Each successful open receives a distinct identifier, even when the same path is opened more than once. Filesystem path support, including mounted shares and UNC paths, depends on the installed filesystem provider and host rather than on fopen itself.
The encoding is the fourth argument after the machine-format slot, for example fopen('data.txt', 'r', 'n', 'UTF-8'). The registry records the normalized encoding for later text operations. Close every successful identifier, including on error paths, and check for -1 before subsequent reads or writes.
Placement and ownership
The active filesystem provider opens the file, while the shared host registry owns its identifier and handle until fclose. There is no GPU file kernel or fusion route. An admitted resident query identifier is gathered only after its resident/class compatibility gates; opening paths and text controls remain host text.
The provider-resident query route preserves the original allocation and returns host character metadata. Explicit device intent does not turn a host file handle into a resident result.
Examples
Open a file for reading
[fid, message] = fopen('data/input.txt', 'r');
assert(fid >= 3, message);
line = fgets(fid);
status = fclose(fid);
lineWrite and inspect a file identifier
[fid, message] = fopen('session.log', 'w', 'ieee-le', 'UTF-8');
assert(fid >= 3, message);
[filename, permission, machinefmt, encoding] = fopen(fid);
fprintf(fid, 'Session started\n');
status = fclose(fid);
filename
permissionAppend binary data
fid = fopen('signals.bin', 'ab+');
assert(fid >= 3);
count = fwrite(fid, [1 2 3], 'double');
status = fclose(fid);
countList open identifiers in RunMat mode
fid = fopen('config.json', 'r');
assert(fid >= 3);
[ids, names] = fopen('all');
found = any(ids == fid);
fclose(fid);
foundHandle a missing file without creating a handle
[fid, message] = fopen('does_not_exist.txt', 'r');
fidExpected output:
fid = -1Query a registered handle
fid = fopen('query.txt', 'r');
assert(fid >= 3);
[name, permission, machinefmt, encoding] = fopen(fid);
status = fclose(fid);
name
machinefmtSelect machine format and text encoding
fid = fopen('format.txt', 'w', 'ieee-be', 'UTF-8');
assert(fid >= 3);
[name, permission, machinefmt, encoding] = fopen(fid);
status = fclose(fid);
machinefmt
encodingUsing fopen with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how fopen changes the result.
Run a small fopen example, explain the result, then change one input and compare the output.
FAQ
Which permissions are accepted?⌄
Use r, w, a, optional +, and optional b or t. Write truncates, append appends, and + enables read/write.
How do I close a file?⌄
Pass the identifier to fclose; the shared registry keeps the handle until it closes.
What happens on open failure?⌄
The first output is double -1, the second is the operating-system message, and later named outputs are empty character values.
What is the default encoding?⌄
Text uses UTF-8 by default. Binary permission uses the binary pseudo-encoding.
Does 'all' list standard streams?⌄
Yes. The listing includes the process standard streams and registered files in RunMat extension mode.
Can I query an invalid identifier?⌄
The query returns empty character metadata when no registry entry exists.
Which machine formats are recorded?⌄
Native, ieee-le, and ieee-be are supported; aliases are normalized before registry publication.
Can the query identifier be integer or resident?⌄
Typed integer, Single, and provider-resident query identifiers have separate RunMat compatibility gates before gathering or registry access.
Can a filename be on a GPU?⌄
No numeric GPU filename is valid text. GPU residency applies only to the gated numeric query-identifier form.
Are handles shared with other file functions?⌄
Yes. fread, fwrite, fprintf, feof, frewind, and fclose use the same host registry.
Can I filter the open-file list?⌄
In RunMat extension mode, fopen('all', machinefmt) filters entries by recorded machine format.
What is returned for a closed file?⌄
Querying its identifier returns empty character metadata; opening the path again creates a new identifier.
Does opening imply a GPU kernel?⌄
No. The file handle remains host-owned; admitted resident query IDs are materialized for metadata lookup.
How do I report a failed open?⌄
Request the second output and use its operating-system message when fid is -1.
Can I open the same file more than once?⌄
Yes. Each successful open owns a separate handle and receives a new identifier.
What about network or UNC paths?⌄
Path resolution is delegated to the installed filesystem provider. Native hosts may accept mounted shares or UNC paths when their operating system permits them; other providers need not.
How do I read lines safely?⌄
Open with read permission, check that the identifier is not -1, read with fgets while checking feof, and close the identifier on both success and failure paths.
Which encoding names can I supply?⌄
Pass the fourth argument after a machine-format placeholder. Common labels include UTF-8, US-ASCII, ISO-8859-1 (latin1), windows-1252, shift_jis, and system; the actual text operation and installed provider determine support.
Related Io functions
Filetext
fclose · feof · fgetl · fgets · fileread · filewrite · 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 fopen is executed, line by line, in Rust.
- View the source for fopen 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.