| MATLAB Function Reference | ![]() |
Syntax
fid = fopen(filename)
fid = fopen(filename,permission)
[fid,message] = fopen(filename,permission,machineformat)
fids = fopen('all')
[filename,permission, machineormat] = fopen(fid)
Description
fid = fopen(filename)
開啟一個檔名為filename的檔案來讀取檔案中的內容。 (在個人電腦上(on PCs), fopen使用二元讀取的方式(binary read access)來開啟檔案。)
fid是檔案識別編號(file identifier),為MATLAB給這個檔案的識別號碼。其他和檔案輸入/輸出的指令都利用fid來指定檔案。若無法開啟檔案,則回傳-1。而fid為1的檔案輸出裝置(standard output)和fid為2的檔案錯誤輸出裝置(standard error)不需要使用者的指令即自動開啟。
fid = fopen(filename,permission)
使用permission的形式來開啟名為filename的檔案。permission可以是:
若檔案是以唯讀方式開啟,filename可以是MATLABPATH的相關路徑。相關路徑是從目前的目錄下開始找起。若找不到該檔案且其開檔方式為唯讀模式,則fopen會到MATLABPATH的路徑下繼續尋找。
檔案可以以二元模式(binary mode)(預設值)或文字模式(text mode)來開啟. 在二元模式下,特定字元不會被特別對待。而在文字模式中,carriage return character會把在換行字元(newline character)後的字刪除,並將這些字移到下一行的前頭. In text mode on the PC, , the carriage return character preceding a newline character is deleted on input and added before the newline character on output. 若想用文字模式開啟檔案,在permission後加一個"t",例如'rt','wt+'(在Unix系統中,文字模式和二元模式沒有任何差異,但在個人電腦(PC)中就差很多了。)
[fid,message] = fopen(filename,permission)
以上面的敘述方式來開啟檔案。若無法開啟, fid為-1,message為系統傳回的錯誤訊息。若成功開啟,message為空字串。
[fid,message] = fopen(filename,permission,machineformat)以指定的permission來開啟檔案,並使用machineformat的格式來讀寫資料。 machineformat可以為下列形式:
fids = fopen('all')
回傳除了1 and 2 (standard output and standard error)之外所有的已被開啟的檔案的file identifiers,並以列向量(row vector)的方式傳回。向量的維度(The number of elements in the vector)就是已被開啟檔案的數量
[filename,permission,machineformat] = fopen(fid)
回傳指定檔案的 filename, permission, 和machineformat。若代表fid的檔案不存在,則回傳空字串。
The 'W' and 'A' permissions are designed for use with tape drives and do not automatically perform a flush of the current output buffer after output operations. For example, open a 1/4" cartridge tape on a SPARCstation for writing with no auto-flush:
fid = fopen('/dev/rst0','W')
Example
這個範例是利用fopen來開啟一個檔案並回傳fid,使其他函式可以利用fid來讀取、關閉檔案。
fid=fopen('fgetl.m');
while 1
tline = fgetl(fid);
if ~ischar(tline), break, end
disp(tline)
end
fclose(fid);
See Also
fclose, ferror, fprintf, fread, fscanf, fseek, ftell, fwrite
| fminsearch | fopen (serial) | ![]() |