Open file or obtain information about open files (2024)

Open file or obtain information about open files

collapse all in page

Syntax

fileID = fopen(filename)

fileID = fopen(filename,permission)

fileID = fopen(filename,permission,machinefmt,encodingIn)

[fileID,errmsg] = fopen(___)

filename = fopen(fileID)

[filename,permission,machinefmt,encodingOut] = fopen(fileID)

Description

example

fileID = fopen(filename) opensthe file, filename, for binary read access, andreturns an integer file identifier equal to or greater than 3. MATLAB® reservesfile identifiers 0, 1, and 2 forstandard input, standard output (the screen), and standard error,respectively.

If fopen cannot open the file, then fileID is -1.

fileID = fopen(filename,permission) opensthe file with the type of access specified by permission.

example

fileID = fopen(filename,permission,machinefmt,encodingIn) additionallyspecifies the order for reading or writing bytes or bits in the fileusing the machinefmt argument. The optional encodingIn argumentspecifies the character encoding scheme associated with the file.

example

[fileID,errmsg] = fopen(___) additionallyreturns a system-dependent error message if fopen failsto open the file. Otherwise, errmsg is an emptycharacter vector. You can use this syntax with any of the input argumentsof the previous syntaxes.

filename = fopen(fileID) returns the file name that a previous call to fopen used when it opened the file specified by fileID. The output filename contains the full path only if the previous fopen call opened the file with r or r+ permissions. The fopen function does not read information from the file to determine the output value.

example

[filename,permission,machinefmt,encodingOut] = fopen(fileID) additionallyreturns the permission, machine format, and encoding that a previouscall to fopen used when it opened the specifiedfile. If the file was opened in binary mode, permission includesthe letter 'b'. The encodingOut outputis a standard encoding scheme name. fopen doesnot read information from the file to determine these output values.An invalid fileID returns empty character vectorsfor all output arguments.

Examples

collapse all

Open File and Pass Identifier to File I/O Function

Open a file and pass the file identifier tothe 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.

fclose(fileID)

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 relevanterror 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-JIScharacter encoding.

fileID = fopen('japanese_out.txt','w','n','Shift_JIS');

The 'w' input specifies write access, the 'n' inputspecifies native byte ordering, and 'Shift_JIS' specifiesthe 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.

fIDs = openedFiles
fIDs = 3

Get the file name and character encoding for the openfile. Use ~ in place of output arguments you wantto omit.

[filename,~,~,encoding] = fopen(fileID)
filename = 'matlabroot\toolbox\matlab\demos\tsunamis.txt'encoding = 'windows-1252'

The output shown here is representative. Your results mightdiffer.

Input Arguments

collapse all

filenameName of file to open
character vector or string scalar

Name of file to open, specified as a character vector or string scalar that includes the file extension.

On UNIX® systems, if filename begins with '~/' or '~username/', the fopen 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 in filename.

If you open a file with read access and the file is not in the current folder, then fopen 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 path name in filename.

Example: 'C:\myFolder\myFile.sample_file.txt'

Example: 'myFolder\sample_file.txt'

Remote Location

If the file is stored at a remote location, then filename must contain the full path of the file specified as a uniform resource locator (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_name
Amazon S3™s3
Windows Azure® Blob Storagewasb, wasbs
HDFS™hdfs

If 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'

Data Types: char | string

permissionFile access type
'r' (default) | 'w' | 'a' | 'r+' | 'w+' | 'a+' | 'A' | 'W' | ...

File access type, specified as a character vector or a stringscalar. 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 binarymode, specify one of the following.

'r'

Open file for reading.

'w'

Open or create new file for writing. Discard existingcontents, if any.

'a'

Open or create new file for writing. Append data to theend of the file.

'r+'

Open file for reading and writing.

'w+'

Open or create new file for reading and writing. Discardexisting contents, if any.

'a+'

Open or create new file for reading and writing. Appenddata to the end of the file.

'A'

Open file for appending without automatic flushing ofthe current output buffer.

'W'

Open file for writing without automatic flushing of thecurrent output buffer.

To open files in text mode, attach the letter 't' tothe permission argument, such as 'rt' or 'wt+'.

On Windows® systems, in text mode:

  • Read operations that encounter a carriage return followedby a newline character ('\r\n') remove the carriagereturn from the input.

  • Write operations insert a carriage return before anynewline character in the output.

Open or create a new file in text mode if you want to writeto it in MATLAB and then open it in Microsoft® Notepad, orany text editor that does not recognize '\n' asa 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 thatincludes a plus sign, '+'.

  • Call fseek or frewind betweenread and write operations. For example, do not call fread followedby fwrite, or fwrite followedby fread, unless you call fseek or frewind betweenthem.

Data Types: char | string

machinefmtOrder for reading or writing bytes or bits
'n' (default) | 'b' | 'l' | 's' | 'a' | ...

Order for reading or writing bytes or bits in the file, specifiedas 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 supportedplatforms use little-endian ordering for new files. Existing binaryfiles can use either big-endian or little-endian ordering.

Data Types: char | string

encodingInCharacter encoding
'UTF-8' | 'ISO-8859-1' | 'windows-1251' | 'windows-1252' | ...

Character encoding to use for subsequent read and write operations, including fscanf, 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

fileIDFile identifier of an open file
integer

File identifier of an open file, specified as an integer.

Data Types: double

Tips

  • In most cases, it is not necessary to open a filein text mode. MATLAB import functions, all UNIX applications,and Microsoft Word and WordPad recognize '\n' asa newline indicator.

Extended Capabilities

Version History

Introduced before R2006a

expand all

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.

This function supports thread-based environments.

See Also

fclose | openedFiles | ferror | fseek | ftell | feof | fscanf | fprintf | fread | fwrite | frewind

MATLAB Command

You clicked a link that corresponds to this MATLAB command:

 

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Open file or obtain information about open files (1)

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

Americas

  • América Latina (Español)
  • Canada (English)
  • United States (English)

Europe

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom (English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)
  • 中国
  • 日本 (日本語)
  • 한국 (한국어)

Contact your local office

Open file or obtain information about open files (2024)

References

Top Articles
Latest Posts
Article information

Author: Mrs. Angelic Larkin

Last Updated:

Views: 6423

Rating: 4.7 / 5 (47 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Mrs. Angelic Larkin

Birthday: 1992-06-28

Address: Apt. 413 8275 Mueller Overpass, South Magnolia, IA 99527-6023

Phone: +6824704719725

Job: District Real-Estate Facilitator

Hobby: Letterboxing, Vacation, Poi, Homebrewing, Mountain biking, Slacklining, Cabaret

Introduction: My name is Mrs. Angelic Larkin, I am a cute, charming, funny, determined, inexpensive, joyous, cheerful person who loves writing and wants to share my knowledge and understanding with you.