fopen - Open file or obtain information about open files - MATLAB (original) (raw)
Open file or obtain information about open files
Syntax
Description
fileID = fopen([filename](#btrnibn-1-filename))
opens the file, filename
, for binary read access, and returns an integer file identifier equal to or greater than 3. MATLAB® reserves file identifiers 0
, 1
, and 2
for standard input, standard output (the screen), and standard error, respectively.
If fopen
cannot open the file, then fileID
is -1
.
fileID = fopen([filename](#btrnibn-1-filename),[permission](#btrnibn-1-permission))
opens the file with the type of access specified by permission
.
fileID = fopen([filename](#btrnibn-1-filename),[permission](#btrnibn-1-permission),[machinefmt](#btrnibn-1-machinefmt),[encodingIn](#btrnibn-1-encodingIn))
additionally specifies the order for reading or writing bytes or bits in the file using the machinefmt
argument. The optional encodingIn
argument specifies the character encoding scheme associated with the file.
[fileID,errmsg] = fopen(___)
additionally returns a system-dependent error message if fopen
fails to open the file. Otherwise, errmsg
is an empty character vector. You can use this syntax with any of the input arguments of the previous syntaxes.
filename = fopen([fileID](#btrnibn-1-fileID))
returns the filename that a previous call to fopen
used when it opened the file specified byfileID
. The output filename
contains the full path only if the previous fopen
call opened the file withr
or r+
permissions. Thefopen
function does not read information from the file to determine the output value.
[filename,permission,machinefmt,encodingOut] = fopen([fileID](#btrnibn-1-fileID))
additionally returns the permission, machine format, and encoding that a previous call to fopen
used when it opened the specified file. If the file was opened in binary mode, permission
includes the letter 'b'
. The encodingOut
output is a standard encoding scheme name. fopen
does not read information from the file to determine these output values. An invalid fileID
returns empty character vectors for all output arguments.
Examples
Open File and Pass Identifier to File I/O Function
Open a file and pass the file identifier to the fgetl
function to read data.
Open the file, tsunamis.txt
, and obtain the file identifier.
fileID = fopen('tsunamis.txt');
Pass the fileID
to the fgetl
function to read one line from the file.
tline =
'A global tsunami data set in xlsx format, comprising the following file:'
Close the file.
Request Name of File to Open
Create a prompt to request the name of a file to open. If fopen
cannot open the file, display the relevant error message.
fileID = -1; errmsg = ''; while fileID < 0 disp(errmsg); filename = input('Open file: ', 's'); [fileID,errmsg] = fopen(filename); end
Open File for Writing and Specify Access Type, Writing Order, Character Encoding
Open a file to write to a file using the Shift-JIS character encoding.
fileID = fopen('japanese_out.txt','w','n','Shift_JIS');
The 'w'
input specifies write access, the 'n'
input specifies native byte ordering, and 'Shift_JIS'
specifies the character encoding scheme.
Get Information About Open Files
Suppose you previously opened a file using fopen
.
fileID = fopen('tsunamis.txt');
Get the file identifiers of all open files.
Get the file name and character encoding for the open file. Use ~
in place of output arguments you want to omit.
[filename,,,encoding] = fopen(fileID)
filename =
'_matlabroot_\toolbox\matlab\demos\tsunamis.txt'
encoding =
'windows-1252'
The output shown here is representative. Your results might differ.
Input Arguments
filename
— Name of file to open
string scalar | character vector
Name of the file to open, specified as a string scalar or character vector that includes the file extension.
On UNIX® systems, if filename
begins with'~/'
or'~_`username`_/'
, thefopen
function expands the path to the current or specified user's home directory, respectively.
Depending on the location of your file, filename
can take on one of these forms.
Current folder or folder on the MATLAB path | Specify the name of the file infilename.If you open a file with read access and the file is not in the current folder, thenfopen searches along the MATLAB search path.If you open a file with write or append access and the file is not in the current folder, then fopen creates a file in the current directory.Example: "sample_file.txt" |
---|---|
Other folders | If the file is not in the current folder or in a folder on the MATLAB path, then specify the full or relative pathname infilename.Example: "C:\myFolder\myFile.sample_file.txt"Example: "myFolder\sample_file.txt" |
Internet URL (since R2024b) | If you specify the file as an internet uniform resource locator (URL), then filename must include the protocol type "http://" or"https://".Example: "http://hostname/path\_to\_file/my\_data.csv" |
Remote location | If the file is stored at a remote location, thenfilename must contain the full path of the file specified as a URL of the form:scheme_name://path_to_file/_my_file.ext_Based on your remote location,scheme_name can be one of the values in this table. Remote Locationscheme_nameAmazon S3™s3Windows Azure® Blob Storagewasb,wasbsHDFS™hdfsIf you are using a cloud file system, set environment variables to communicate with the remote file system. For more information, see Work with Remote Data.Files in a Hadoop Distributed File System (HDFS) volume cannot be opened in read-write mode.Example: "s3://bucketname/path_to_file/sample_file.txt" |
Example: "myFile.txt"
permission
— File access type
'r'
(default) | 'w'
| 'a'
| 'r+'
| 'w+'
| 'a+'
| 'A'
| 'W'
| ...
File access type, specified as a character vector or a string scalar. You can open a file in binary mode or in text mode. On UNIX systems, both translation modes have the same effect. To open a file in binary mode, specify one of the following.
'r' | Open file for reading. |
---|---|
'w' | Open or create new file for writing. Discard existing contents, if any. |
'a' | Open or create new file for writing. Append data to the end of the file. |
'r+' | Open file for reading and writing. |
'w+' | Open or create new file for reading and writing. Discard existing contents, if any. |
'a+' | Open or create new file for reading and writing. Append data to the end of the file. |
'A' | Open file for appending without automatic flushing of the current output buffer. |
'W' | Open file for writing without automatic flushing of the current output buffer. |
To open files in text mode, attach the letter 't'
to the permission
argument, such as 'rt'
or 'wt+'
.
On Windows® systems, in text mode:
- Read operations that encounter a carriage return followed by a newline character (
'\r\n'
) remove the carriage return from the input. - Write operations insert a carriage return before any newline character in the output.
Open or create a new file in text mode if you want to write to it in MATLAB and then open it in Microsoft® Notepad, or any text editor that does not recognize '\n'
as a newline sequence. When writing to the file, end each line with '\r\n'
. For an example, see fprintf. Otherwise, open files in binary mode for better performance.
To read and write to the same file:
- Open the file with a value for
permission
that includes a plus sign,'+'
. - Call
fseek
orfrewind
between read and write operations. For example, do not callfread
followed byfwrite
, orfwrite
followed byfread
, unless you callfseek
orfrewind
between them.
Data Types: char
| string
machinefmt
— Order for reading or writing bytes or bits
'n'
(default) | 'b'
| 'l'
| 's'
| 'a'
| ...
Order for reading or writing bytes or bits in the file, specified as one of the following character vectors or string scalars.
'n' or 'native' | Your system byte ordering (default) |
---|---|
'b' or 'ieee-be' | Big-endian ordering |
'l' or 'ieee-le' | Little-endian ordering |
's' or 'ieee-be.l64' | Big-endian ordering, 64-bit long data type |
'a' or 'ieee-le.l64' | Little-endian ordering, 64-bit long data type |
By default, all currently supported platforms use little-endian ordering for new files. Existing binary files can use either big-endian or little-endian ordering.
Data Types: char
| string
encodingIn
— Character encoding
'UTF-8'
| 'ISO-8859-1'
| 'windows-1251'
| 'windows-1252'
| ...
Character encoding to use for subsequent read and write operations, includingfscanf
, fprintf
,fgetl
, fgets
,fread
, and fwrite
, specified as a character vector or a string scalar. The character vector or string scalar must contain a standard character encoding scheme name such as the following.
"Big5" | "ISO-8859-1" | "windows-874" |
---|---|---|
"Big5-HKSCS" | "ISO-8859-2" | "windows-949" |
"CP949" | "ISO-8859-3" | "windows-1250" |
"EUC-KR" | "ISO-8859-4" | "windows-1251" |
"EUC-JP" | "ISO-8859-5" | "windows-1252" |
"EUC-TW" | "ISO-8859-6" | "windows-1253" |
"GB18030" | "ISO-8859-7" | "windows-1254" |
"GB2312" | "ISO-8859-8" | "windows-1255" |
"GBK" | "ISO-8859-9" | "windows-1256" |
"IBM866" | "ISO-8859-11" | "windows-1257" |
"KOI8-R" | "ISO-8859-13" | "windows-1258" |
"KOI8-U" | "ISO-8859-15" | "US-ASCII" |
"Macintosh" | "UTF-8" | |
"Shift_JIS" |
If you do not specify an encoding scheme when opening a file for reading,fopen
uses auto character-set detection to determine the encoding. If you do not specify an encoding scheme when opening a file for writing, fopen
defaults to using UTF-8 in order to provide interoperability between all platforms and locales without data loss or corruption. For more information, see Import Text Data Files with Low-Level I/O.
If you specify a value for encoding that is not in the list of supported values, MATLAB issues a warning. Specifying other encoding names sometimes (but not always) produces correct results.
Data Types: char
| string
fileID
— File identifier of an open file
integer
File identifier of an open file, specified as an integer.
Data Types: double
Limitations
- MATLAB does not support internet URLs that require authentication.
- MATLAB Online™ supports internet URLs associated with Microsoft OneDrive™ files and folders, while the installed version of MATLAB supports only local OneDrive files.
Tips
- In most cases, it is not necessary to open a file in text mode. MATLAB import functions, all UNIX applications, and Microsoft Word and WordPad recognize
'\n'
as a newline indicator.
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
- Code generation does not support:
- The input arguments
machinefmt
,encodingIn
, orfileID
. - The output argument
errmsg
. - The syntax
fopen('all')
. - Opening a file in text mode. That is the
permission
argument must not contain the lettert
. For example, the value cannot be'rt'
.
- The input arguments
- The
permission
argument can contain three characters at most. The characters must be unique. - If you disable extrinsic calls, then you cannot return file identifiers created with
fopen
to MATLAB functions or extrinsic functions. Use these file identifiers only internally. - When generating C/C++ executables, static libraries, or dynamic libraries, you can open up to 20 files.
- The generated code does not report errors from invalid file identifiers. Write your own file open error handling in your MATLAB code. Test whether
fopen
returns-1
, which indicates that the file open failed. For example:
...
fid = fopen(filename, 'r');
if fid == -1
% fopen failed
else
% fopen successful, okay to call fread
A = fread(fid);
...
- The behavior of the generated code for
fread
is compiler-dependent when you:- Open a file using
fopen
with apermission
ofa+
. - Read the file using
fread
before calling an I/O function, such asfseek
orfrewind
, that sets the file position indicator.
- Open a file using
Thread-Based Environment
Run code in the background using MATLAB® backgroundPool
or accelerate code with Parallel Computing Toolbox™ ThreadPool
.
Usage notes and limitations:
- The
fopen('all')
syntax is not supported in thread-based environments.
Version History
Introduced before R2006a
R2024b: Read data over HTTP and HTTPS using low-level file functions
You can read data from primary online sources by performing low-level file read operations over an internet URL.
R2024a: fopen("all")
syntax will be removed
The fopen("all")
syntax will be removed in a future release. To get the file identifiers of all open files, use the openedFiles function instead.
R2022b: Use function in thread-based environments
This function supports thread-based environments.