fopen
Opens a file and returns a file identifier.
Category: Data Import and Analysis > Data Import and Export
Syntax
fid = fopen(filename)
Opens the file for reading.
fid = fopen(filename, permission)
Opens with a mode such as 'w', 'a', 'r+'; add t for text mode.
[fid, msg] = fopen(...)
Also returns an error message when the open fails.
[name, perm, machinefmt, enc] = fopen(fid)
Queries the properties of an open file.
Description
fopen does not raise an error when a file is missing. It returns -1, so check the result before reading. The identifiers 0, 1 and 2 are reserved for standard input, standard output and standard error.
Every file opened should be closed with fclose.
Input arguments
filename- Name of the file.
permission'r'read (default),'w'write and truncate,'a'append,'r+'read and write,'w+'and'a+'for update variants.
Output arguments
fid- Integer identifier, 3 or greater, to pass to other file functions;
-1if the file could not be opened. msg- Text describing why opening failed.
Example
Open for reading, with a failing case
[fid, msg] = fopen('missing.txt')
fid = fopen('ok.txt', 'w');
fprintf(fid, 'hi');
fclose(fid);
fid = fopen('ok.txt');
[name, perm] = fopen(fid)
fclose(fid);
Output
fid = -1
msg = 'No such file or directory'
name = 'ok.txt'
perm = 'r'