Programming |
Opening Files
Before reading or writing a text or binary file, you must open it with the fopen
command.
Specifying the Permission 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 might 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:
If fopen
fails, for example if you try to open a file that does not exist, fopen
-1
to the file identifier.
ferror
can also provide information about errors.
Test the file identifier each time you open a file in your code. For example, this code loops until 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
When you run this code, if you specify a file that doesn't exist, such as nofile.mat
, at the Open file:
prompt, the results are
If you specify a file that does exist, such as goodfile.mat
, the code example returns the file identifier, fid
, and exits the loop.
Opening Temporary Files and Directories
The tempdir
and tempname
functions assist in locating temporary data on your system.
Function |
Purpose |
|
Get temporary directory name. |
|
Get temporary filename. |
Use these functions to create temporary files. Some systems delete temporary files every time you reboot the system. On other systems, designating a file as temporary can mean only that the file is not backed up.
The tempdir
function 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:
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 |
© 1994-2005 The MathWorks, Inc.