Note Closing a file does not clear the file identifier variable fid . However, subsequent attempts to access a file through this file identifier variable will not work.
15 File I/O 15-6 Temporary Files and Directories The tempdir and tempname commands assist in locating temporary data on your system. 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. Function Purpose tempdir Get temporary directory name. tempname Get temporary filename.
Binary Files 15-7 Binary Files This section explains how to read from or write to binary files. Reading Binary Files The fread function reads all or part of a binary file (as specified by a file identifier) and stores it in a matrix. In its simplest form, it reads an entire file and interprets each byte of input as the next element of the matrix. For example, the following code reads the data from a file named nickel.dat into matrix A . fid = fopen(’nickel.dat’,’r’); A = fread(fid); To echo the data to the screen after reading it, use char to display the contents of A as characters, transposing the data so it displays horizontally: disp(char(A’)) The char function causes MATLAB to interpret the contents of A as characters instead of as numbers. Transposing A displays it in its more natural horizontal format. Controlling the Number of Values Read fread accepts an optional second argument that controls the number of values read (if unspecified, the default is the entire file). For example, this statement reads the first 100 data values of the file specified by fid into the column vector A : A = fread(fid,100); Replacing the number 100 with the matrix dimensions [10 10] reads the same 100 elements into a 10-by-10 array. Function Purpose fread Read binary data from file. fwrite Write binary data to file.
15 File I/O 15-8 Controlling the Data Type of Each Value An optional third argument to fread controls the data type of the input. The data type argument controls both the number of bits read for each value and the interpretation of those bits as character, integer, or floating-point values.
- Spring '16
- chun sang yoo