RunMat
  • Pricing
RunMat
GitHub
GitHub
Sign inTry in browser
DesktopRuntimePhysicsCADAdministrationAgent

Get RunMat updates

New releases, guides and examples.

Product+
  • Runtime
  • GPU
  • Parallel
  • Compile
  • Interop and MEX
  • Simulation
  • MCAD
  • ECAD
  • Enterprise
  • AI integrations
  • Pricing
  • Download
Math+
  • Signal processing
  • Linear algebra
  • Statistics
  • Curve fitting
  • Differential equations
  • Control systems
  • Optimization
  • Finance
  • Data and tables
  • Plotting
Physics+
  • Simulation overview
  • Structural
  • Thermal
  • Electromagnetic
  • Joule heating
  • Thermal stress
  • Acoustics
  • Fluid flow
  • Conjugate heat transfer
  • Fluid–structure
  • What is FEA
Industries+
  • Aerospace
  • Automotive and transportation
  • Defense
  • Electronics and semiconductors
  • Energy
  • Industrial machinery
  • Life sciences
  • Quantitative finance
Learn+
  • Guides
  • Docs
  • Function reference
  • Language reference
  • Migration guide
  • Changelog
  • MATLAB Online
  • MATLAB AI agent
  • For students
Compare+
  • RunMat vs MATLAB
  • RunMat vs Ansys
  • RunMat vs SOLIDWORKS
  • RunMat vs Altium
  • RunMat vs Cadence
  • RunMat vs COMSOL
  • RunMat vs Python
  • RunMat vs Julia
  • RunMat vs Physics AI
  • RunMat vs Octave
  • Benchmarks
  • MATLAB alternatives
  • All comparisons
Company+
  • About
  • Blog
  • Contact
  • Source code↗
  • License
  • Privacy
  • Terms

Product

  • Runtime
  • GPU
  • Parallel
  • Compile
  • Interop and MEX
  • Simulation
  • MCAD
  • ECAD
  • Enterprise
  • AI integrations
  • Pricing
  • Download

Math

  • Signal processing
  • Linear algebra
  • Statistics
  • Curve fitting
  • Differential equations
  • Control systems
  • Optimization
  • Finance
  • Data and tables
  • Plotting

Physics

  • Simulation overview
  • Structural
  • Thermal
  • Electromagnetic
  • Joule heating
  • Thermal stress
  • Acoustics
  • Fluid flow
  • Conjugate heat transfer
  • Fluid–structure
  • What is FEA

Industries

  • Aerospace
  • Automotive and transportation
  • Defense
  • Electronics and semiconductors
  • Energy
  • Industrial machinery
  • Life sciences
  • Quantitative finance

Learn

  • Guides
  • Docs
  • Function reference
  • Language reference
  • Migration guide
  • Changelog
  • MATLAB Online
  • MATLAB AI agent
  • For students

Compare

  • RunMat vs MATLAB
  • RunMat vs Ansys
  • RunMat vs SOLIDWORKS
  • RunMat vs Altium
  • RunMat vs Cadence
  • RunMat vs COMSOL
  • RunMat vs Python
  • RunMat vs Julia
  • RunMat vs Physics AI
  • RunMat vs Octave
  • Benchmarks
  • MATLAB alternatives
  • All comparisons

Company

  • About
  • Blog
  • Contact
  • Source code↗
  • License
  • Privacy
  • Terms
GitHubXLinkedIn

© Dystr, Inc. · RunMat v0.7.1, Nov 17, 2026

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

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.
NameTypeRequiredDefaultDescription
filenameAnyYes—Path to file to open.
permissionStringScalarNo"r"Permission string such as 'r', 'w', 'a', optionally with '+'/'b'/'t'.
machinefmtStringScalarNo"native"Machine-format label.
encodingStringScalarNo"UTF-8"Encoding label.
fidNumericScalarYes—Numeric file identifier.
selectorStringScalarYes"all"Literal selector 'all'.
machinefmtStringScalarNo—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.
NameTypeDescription
fidNumericScalarFile identifier on success, or -1 on failure.
msgStringScalarOpen failure message string (empty on success).
machinefmtStringScalarResolved machine-format label for the opened stream.
encodingStringScalarResolved encoding label for the opened stream.
filenameStringScalarFilename associated with queried file identifier.
permissionStringScalarCanonical fopen permission string.
machinefmtStringScalarMachine-format label of queried stream.
encodingStringScalarEncoding label of queried stream.
fidsNumericArrayColumn vector of open user file identifiers.
namesAnyCell column of display names.
machinefmtsAnyCell column of machine-format labels.
encodingsAnyCell 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
IdentifierWhenMessage
RunMat:fopen:InvalidInputArgument count or argument shape/type is invalid.fopen: invalid input arguments
RunMat:fopen:InvalidPermissionPermission string is invalid or unsupported.fopen: invalid permission string
RunMat:fopen:InvalidMachineFormatMachine-format argument is invalid or unsupported.fopen: invalid machine format
RunMat:fopen:InvalidEncodingEncoding argument is invalid.fopen: invalid encoding
—Internal runtime conversion/control-flow operation fails.fopen: internal error

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);
line

Write 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
permission

Append binary data

fid = fopen('signals.bin', 'ab+');
assert(fid >= 3);
count = fwrite(fid, [1 2 3], 'double');
status = fclose(fid);
count

List open identifiers in RunMat mode

fid = fopen('config.json', 'r');
assert(fid >= 3);
[ids, names] = fopen('all');
found = any(ids == fid);
fclose(fid);
found

Handle a missing file without creating a handle

[fid, message] = fopen('does_not_exist.txt', 'r');
fid

Expected output:

fid = -1

Query a registered handle

fid = fopen('query.txt', 'r');
assert(fid >= 3);
[name, permission, machinefmt, encoding] = fopen(fid);
status = fclose(fid);
name
machinefmt

Select 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
encoding

Using 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

Net

accept · read · readline · tcpclient · tcpserver · write

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

Audio

audioinfo · audioread

Io

clc · diary · disp · display · format · input

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

Archive

gunzip · gzip · unzip

Hdf5

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

Import

importdata · textscan

Json

jsondecode · jsonencode

Mat

load · matfile · matlab.io.MatFile.subsasgn · matlab.io.MatFile.subsref · save

Http

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

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.

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
  • Open, query, and list
  • Placement and ownership
  • Examples
  • Open a file for reading
  • Write and inspect a file identifier
  • Append binary data
  • List open identifiers in RunMat mode
  • Handle a missing file without creating a handle
  • Query a registered handle
  • Select machine format and text encoding
  • Using fopen with coding agents
  • FAQ
  • Related Io functions
  • Filetext
  • Net
  • Repl Fs
  • Tabular
  • Audio
  • Io
  • Data
  • Archive
  • Hdf5
  • Import
  • Json
  • Mat
  • Http
  • Source you can read
  • About RunMat