fopen

Opens a file, filename, for read/write operations.

Syntax

fileID = fopen(filename)

fileID = fopen(filename, mode)

[fileID, msg] = fopen(filename, mode)

[filepath, filemode] = fopen(fileID)

Inputs

filename
Filename or the path to the file to be opened or created.
Type: string
mode
Additional argument which specifies the mode with which filename is opened. Default mode is 'rb'. Apart from the valid modes listed below, 't' or 'b' can be appended to specify text or binary modes.
r
Opens an existing file for read operation(s).
w
Opens a file for write operation(s), overwriting previous content.
a
Opens a file for append operation(s). A new file is created if filename does not exist.
r+
Opens an existing file for read and write operation(s).
w+
Opens a file for read and write operation(s), overwriting previous contents if applicable.
a+
Opens a file for read and append operation(s).
Type: string
fileID
File ID returned from an earlier call to fopen().
When the first argument is a fileID, fopen returns information about the opened file.
Type: integer

Outputs

fileID
Integer representing the file ID of filename.
fileID is specified in other functions to operate on this file. fileID is -1 if there is an error with opening the file.
Type: integer
msg
If an error occurs opening the file, msg contains a system message describing the error.
Type: string
filepath
Path to the opened file, if a valid fileID is given.
Type: string
mode
String representation of the current mode associated with the file ID.
Type: string

Example

% Example fopen/fwrite/fclose
[fopen_fileID, fopen_msg] = fopen('testfile', 'w')
[fopen_path, fopen_mode] = fopen(fopen_fileID)
fwrite(fopen_fileID, sprintf('testoutput\r\n'), 'char');
printf('fclose return %d', fclose(fopen_fileID))
fopen_fileID = 5
fopen_msg = 
fopen_path = testfile
fopen_mode = wb
fclose return 0