next up previous contents
Next: FCLOSE File Close Function Up: Input/Ouput Functions Previous: GETPRINTLIMIT Get Limit For   Contents

Subsections

FOPEN File Open Function

Usage

Opens a file and returns a handle which can be used for subsequent file manipulations. The general syntax for its use is

  fp = fopen(fname,mode,byteorder)

Here fname is a string containing the name of the file to be opened. mode is the mode string for the file open command. The first character of the mode string is one of the following:

On some platforms (e.g. Win32) it is necessary to add a 'b' for binary files to avoid the operating system's 'CR/LF<->CR' translation.

Finally, FreeMat has the ability to read and write files of any byte-sex (endian). The third (optional) input indicates the byte-endianness of the file. If it is omitted, the native endian-ness of the machine running FreeMat is used. Otherwise, the third argument should be one of the following strings:

If the file cannot be opened, or the file mode is illegal, then an error occurs. Otherwise, a file handle is returned (which is an integer). This file handle can then be used with fread, fwrite, or fclose for file access.

Note that three handles are assigned at initialization time:

These handles cannot be closed, so that user created file handles start at 3.

Examples

Here are some examples of how to use fopen. First, we create a new file, which we want to be little-endian, regardless of the type of the machine. We also use the fwrite function to write some floating point data to the file.

--> fp = fopen('test.dat','wb','ieee-le')
fp = 
  <uint32>  - size: [1 1]
            3  
--> fwrite(fp,float([1.2,4.3,2.1]))
ans = 
  <uint32>  - size: [1 1]
            3  
--> fclose(fp)

Next, we open the file and read the data back

--> fp = fopen('test.dat','rb','ieee-le')
fp = 
  <uint32>  - size: [1 1]
            3  
--> fread(fp,[1,3],'float')
ans = 
  <float>  - size: [1 3]
 
Columns 1 to 3
    1.2000000          4.3000002          2.0999999       
--> fclose(fp)

Now, we re-open the file in append mode and add two additional floats to the file.

--> fp = fopen('test.dat','a+','le')
fp = 
  <uint32>  - size: [1 1]
            3  
--> fwrite(fp,float([pi,e]))
ans = 
  <uint32>  - size: [1 1]
            2  
--> fclose(fp)

Finally, we read all 5 float values from the file

--> fp = fopen('test.dat','rb','ieee-le')
fp = 
  <uint32>  - size: [1 1]
            3  
--> fread(fp,[1,5],'float')
ans = 
  <float>  - size: [1 5]
 
Columns 1 to 3
    1.2000000          4.3000002          2.0999999       
 
Columns 4 to 5
    3.1415927          2.7182817       
--> fclose(fp)


next up previous contents
Next: FCLOSE File Close Function Up: Input/Ouput Functions Previous: GETPRINTLIMIT Get Limit For   Contents
Samit K. Basu 2005-03-16