RunMat
  • Pricing
RunMat
GitHub
GitHub
DownloadSign InTry in Browser
DesktopRuntimeServer
RunMat

Run math blazing fast

GitHubX (Twitter)LinkedIn

Company

  • About
  • Pricing
  • Contact

Explore

  • RunMat for academia
  • RunMat vs MATLAB Online
  • Benchmarks

Get product updates and release notes from the RunMat team.

© 2026 Dystr · Made withfor the scientific community.

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.

LicensePrivacy
/
See all docs
Builtin Reference
    • fclose
    • feof
    • fgetl
    • fgets
    • fileread
    • filewrite
    • fopen
    • fprintf
    • fread
    • frewind
    • fwrite
    • readlines
    • writelines

fopen — Open files and return file identifiers in MATLAB and RunMat.

fopen opens a file and returns a double file identifier (fid) used by other I/O builtins. Permission strings, machine-format specifiers, encoding handling, and metadata query forms follow MATLAB semantics. Legacy no-argument and 'all' listing forms are explicit RunMat extensions.

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

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

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

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

How fopen works

  • fid = fopen(filename) opens an existing file for reading. The call fails (returning fid = -1) when the file cannot be opened.
  • fid = fopen(filename, permission) opens a file using the requested permission string ('r', 'w', 'a', 'r+', 'w+', 'a+', plus optional 'b'/'t'). Permissions map to the same semantics as MATLAB: 'w' truncates, 'a' appends, and '+' enables reading and writing.
  • fid = fopen(filename, permission, machinefmt, encoding) records the requested machine format ('native', 'ieee-le', 'ieee-be') and text encoding (defaults to UTF-8 in text mode, binary otherwise) for later inspection.
  • [fid, message] = fopen(...) returns an empty character vector on success and the operating-system error message on failure.
  • [filename, permission, machinefmt, encodingOut] = fopen(fid) queries an existing file identifier.
  • In runmat compatibility mode, [fid_list, names, machinefmts, encodings] = fopen('all') lists open streams and files; the compatibility target removed the legacy 'all' selector in favor of openedFiles, so no-argument and 'all' forms are rejected in MATLAB-compatible modes.
  • In runmat compatibility mode, [fid_list, names] = fopen('all', machinefmt) additionally filters the legacy listing by recorded machine format.
  • The compatibility target documents double query identifiers. RunMat independently gates typed integer, single, and provider-resident query identifiers before gather; integer identifiers are checked exactly against the registry domain.

Does RunMat run fopen on the GPU?

fopen always executes on the CPU. When a filename argument resides on a GPU array, RunMat gathers it to host memory before opening the file. File identifiers and their associated metadata are managed by a host-side registry that other builtins (such as fclose, fread, and fwrite) consult.

Examples

Open a File for Reading

[fid, message] = fopen('data/input.txt', 'r');
if fid == -1
    error('Failed to open file: %s', message);
end

Write Text to a New File

[fid, message] = fopen('logs/session.log', 'w');
if fid == -1
    error('Failed to create log file: %s', message);
end
fprintf(fid, 'Session started\n');
fclose(fid)

Append Binary Data

[fid, message] = fopen('signals.bin', 'ab+');
if fid == -1
    error('Failed to open binary log: %s', message);
end
fwrite(fid, rand(1, 1024), 'double');
fclose(fid)

Query File Metadata

fid = fopen('config.json');
[filename, permission, machinefmt, encoding] = fopen(fid);
disp(filename);
disp(permission);
fclose(fid)

List All Open Files

[fid_list, names] = fopen('all');
disp(fid_list);
disp(names)

Handle Missing Files Gracefully

[fid, message] = fopen('does_not_exist.txt', 'r');
if fid == -1
    fprintf('Failed to open file: %s\n', message);
end

Specify Machine Format and Encoding

[fid, message, machinefmt, encoding] = fopen('report.txt', 'w', 'ieee-le', 'latin1');
if fid == -1
    error('Failed to open report: %s', message);
end
fprintf(fid, 'olá mundo');
fclose(fid)

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

What values can I use for the permission argument?⌄

Use the same strings MATLAB accepts: 'r', 'w', 'a', optionally combined with '+' and 'b'/'t'. For example, 'r+' opens an existing file for reading and writing, 'wb' opens a binary file for writing (truncating any existing content), and 'ab+' appends to a binary file while permitting reads.

How do I close a file after opening it?⌄

Call fclose(fid) with the file identifier returned by fopen. RunMat tracks open handles in a registry so that fclose, fread, and fwrite can reuse the same identifier.

What happens if fopen fails?⌄

fopen returns fid = -1 and the second output argument contains the OS error message. The third and fourth outputs are empty character vectors when opening fails.

Which encoding does RunMat use by default?⌄

Text-mode files default to UTF-8 unless you specify the encoding argument. Binary permissions ('...b') implicitly use the pseudo-encoding binary.

Does fopen('all') include standard input and output?⌄

Only in runmat compatibility mode. The compatibility target removed fopen('all'); RunMat preserves the legacy listing as an explicitly gated extension.

Are machine formats honoured during reads and writes?⌄

RunMat records the requested machine format so that fread/fwrite can apply byte-order conversions. Hosts default to 'native', while passing 'ieee-le' or 'ieee-be' forces little or big-endian interpretation respectively.

Can I open the same file multiple times?⌄

Yes. Each successful call to fopen registers a new handle with its own identifier, even if the path string matches an existing entry.

Does fopen support network paths or UNC shares?⌄

RunMat relies on the operating system for path resolution, so UNC paths and mounted network shares are supported as long as the OS can open them.

What does fopen do in MATLAB?⌄

fopen opens a file and returns a file identifier (fid) used by subsequent I/O functions like fread, fwrite, fprintf, and fclose. If the file cannot be opened, it returns -1.

How do I read a text file line by line in MATLAB?⌄

Open the file with fid = fopen('file.txt', 'r'), then loop with fgets(fid) until feof(fid) returns true, and finally close with fclose(fid). RunMat supports this same pattern.

What file modes does fopen support?⌄

fopen supports 'r' (read), 'w' (write, creates or overwrites), 'a' (append), 'r+' (read and write), 'w+' (read and write, truncates), and 'a+' (read and append).

How do I read a file with a specific encoding?⌄

Pass the encoding as the fourth argument after the machine-format placeholder, for example fid = fopen('data.txt', 'r', 'n', 'UTF-8'). RunMat accepts 'UTF-8', 'US-ASCII', 'ISO-8859-1' (alias 'latin1'), 'windows-1252', 'shift_jis', and 'system'.

Do I need to fclose every file I open?⌄

Yes. Every successful fopen registers a handle that holds OS resources until you call fclose(fid). For robust code, tie the close to an onCleanup object so the file is released even if your code errors partway through:

fid = fopen('data.txt', 'r');
cleanup = onCleanup(@() fclose(fid));
% ... use fid freely ...
Should I always check the return value of fopen?⌄

Yes. Request two outputs so you can surface a useful error message: [fid, errmsg] = fopen(filename, 'r'); if fid == -1, error(errmsg); end. Without this guard, subsequent calls like fread(fid) fail with a generic invalid-identifier error that hides the real cause.

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 · 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

Audio

audioinfo · audioread

Io

clc · diary · disp · display · format · input

Archive

gunzip · gzip · unzip

Hdf5

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

Import

importdata · textscan

Json

jsondecode · jsonencode

Mat

load · matfile · save

Http

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

Open-source implementation

Unlike proprietary runtimes, every RunMat function is open-source. 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 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.

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
  • How fopen works
  • Does RunMat run fopen on the GPU?
  • Examples
  • Open a File for Reading
  • Write Text to a New File
  • Append Binary Data
  • Query File Metadata
  • List All Open Files
  • Handle Missing Files Gracefully
  • Specify Machine Format and Encoding
  • Using fopen with coding agents
  • FAQ
  • Related Io functions
  • Filetext
  • Net
  • Repl Fs
  • Tabular
  • Audio
  • Io
  • Archive
  • Hdf5
  • Import
  • Json
  • Mat
  • Http
  • Open-source implementation
  • About RunMat