Opens a file for reading. Returns an integer file ID to be used to for reference later.


fileID = fopen(filename)

fileID = fopen(filename, 'mode')

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

[filepath, filemode] = fopen(fileID)


Filename or the path to the file to be opened.
Type: char | string
Input or output method attributed to the opened file.
When the first argument is a filename, the default mode is 'r' to read an existing file.
See Comments for addition mode values.
Type: char | string
File ID returned from an earlier call to fopen().
When the first argument is a fileID, fopen returns information about the opened file.
Type: double | integer


Integer representing the file ID of filename.
fileID will be specified in other functions to operate on this file.
fileID will be -1 if an error occurs opening the file.
If an error occurs opening the file, msg will contain a system message describing the error.
String representation of the path to specified file.
String representation of current mode associated with the file ID.


% 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


When requested with multiple outputs can return the file ID, error, path or mode specified. When called with multiple inputs second input can be various modes. Valid modes include:
  • 'r': Opens a file for reading, this is the default mode if none is given.
  • 'w': Opens a file for writing. An existing file is deleted.
  • 'a': Opens or creates a file for writing (appending) at the end of the file.
  • 'r+': Opens an existing file for reading and writing.
  • 'w+': Opens a file for reading or writing. The previous contents are discarded.
  • 'a+': Opens or creates a file for reading or writing (appending) at the end of the file.