Programming Previous page   Next Page

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

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

Test the file identifier each time you open a file in your code. For example, this code loops until a readable filename is entered:

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
tempdir
Get temporary directory name.
tempname
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:


Previous page  Using Low-Level File I/O Functions Reading Binary Data Next page

© 1994-2005 The MathWorks, Inc.