Development Environment | ![]() ![]() |
Opening Files
Before reading or writing a text or binary file, you must open it with the fopen
command.
fid = fopen('filename','permission')
Specifying the Permissions String
The permission
string specifies the kind of access to the file you require. Possible permission
strings include:
Note
Systems such as Microsoft Windows that distinguish between text and binary files may require additional characters in the permission string, such as 'rb' to open a binary file for reading.
|
Using the Returned File Identifier (fid)
If successful, fopen
returns a a nonnegative integer, called a file identifier (fid
). You pass this value as an argument to the other I/O functions to access the open file. For example, this fopen
statement opens the data file named penny.dat
for reading.
fid = fopen('penny.dat','r')
If fopen
fails, for example if you try to open a file that does not exist, fopen
:
-1
to the file identifier.ferror
may also provide information about errors.It's good practice to test the file identifier each time you open a file in your code. For example, this code loops a readable filename is entered.
fid=0; while fid < 1 filename=input('Open file: ', 's'); [fid,message] = fopen(filename, 'r'); if fid == -1 disp(message) end end
Now assume that nofile.mat
does not exist but that goodfile.mat
does exist. On one system, the results are
Open file: nofile.mat Cannot open file. Existence? Permissions? Memory? . . . Open file: goodfile.mat
Opening Temporary Files and Directories
The tempdir
and tempname
commands assist in locating temporary data on your system.
Function |
Purpose |
|
Get temporary directory name. |
|
Get temporary filename. |
You can create temporary files. Some systems delete temporary files every time you reboot the system. On other systems, designating a file as temporary may mean only that the file is not backed up.
A function named tempdir
returns the name of the directory or folder that has been designated to hold temporary files on your system. For example, issuing tempdir
on a UNIX system returns the /tmp
directory.
MATLAB also provides a tempname
function that returns a filename in the temporary directory. The returned filename is a suitable destination for temporary data. For example, if you need to store some data in a temporary file, then you might issue the following command first.
fid = fopen(tempname, 'w');
Note
The filename that tempname generates is not guaranteed to be unique; however, it is likely to be so.
|
![]() | Using Low-Level File I/O Functions | Reading Binary Data | ![]() |