(translator=pacific, ChineseSource=pacific-20020502-12.5\fprintf.html, EnglishSource=c:\matlabr12\help\techdoc\ref\fprintf.html)
MATLAB Function Reference    
fprintf

將格式化的資料寫入檔案中

Syntax

Description

count = fprintf(fid,format,A,...) format 所指定的格式來將矩陣A(和其他額外的矩陣)中的資料格式化,並寫到以fid為識別編號的檔案中。fprintf 回傳所寫入的byte數

 fid 是從 fopen. (也有可能是代表檔案輸出裝置(螢幕)的 1 或檔案錯誤輸出裝置的2 , 可參閱 fopen )中所得到的檔案識別編號(file identifier)。 未設定 fid 則會列印在螢幕上。

Format String

 format 引數中包含了 C語言中的轉換規格(conversion specifications)。轉換規格(conversion specifications)包含了表示格式(notation)、對齊格式(alignment)、有意義的數字(significant digits)、表示長度(field width)和其他有關輸出的格式。 字串中還可包含像換行字元 (newline characters)和tab等等不會被印出的跳脫字元(escape characters)。

轉換規格(conversion specifications) 以 % 字元作開始,並包括下列必要或非必要的元素:

利用下列順序表示之:

Flags

利用旗標(Flags)來控制對齊的方式。

符號
說明
範例
負號 (-)
把引數靠左對齊。 %-5.2d
正號 (+)
永遠表示正負號(+ or -)。
%+5.2d
零 (0)
將空白部分以0來代替。
%05.2d

Field Width and Precision Specifications

可以利用下列項目來控制表示長度和精確度

項目
說明
Example
表示長度(Field width)
數字決定至少要印幾位數字出來。
%6f
精確度(Precision)
包含點 (.)的數字決定小數點右邊要印出幾位數字出來。
%6.2f

Conversion Characters

轉換字元(Conversion characters)指定了輸出的格式和形態。

指定符號
說明
%c
單一字元
%d
有正負號的十進位表示法
%e
指數表示法(Exponential notation)(使用小寫的e,例如 3.1415e+00)
%E
指數表示法(Exponential notation)(使用大寫的E,例如 3.1415e+00)
%f
固定浮點數表示法(Fixed-point notation)
%g
 The more compact of %e or %f, as defined in [2]. 不重要的0不會顯元
%G
除了使用大寫的E外,和 %g相同。
%o
沒有正負號的八進位表示法。
%s
一連串字元所組成的字串
%u
 沒有正負號的十進位表示法
%x
十六進位表示法 (使用小寫的 a-f)
%X
十六進位表示法 (使用大寫的 A-F)

轉換字元(Conversion characters) %o, %u, %x, 和 %X 支援子形態指定(subtype specifier)。詳細請參考 Remarks

Escape Characters

下表中列出不會印出的跳脫字元(escape character sequences)。
字元
敘述
\b
倒退刪除(Backspace)
\f
Form feed
\n
換行字元(new line)
\r
Carriage return
\t
Horizontal tab
\\
反斜線(Backslash)

\'' or ''

(two single quotes)

單引號(Single quotation mark)
%%
百分比字元(Percent character)

Remarks

 fprintf 和ANSI C語言中的fscanf的用法十分相似,也有下列特性

Examples

下列程式

產生 exp.txt 檔案並包括下列內容:

下列指令:

在螢幕上印出

若要印出一個單引號,要用連續二個單引號,範例如下:

在螢幕上印出

下列指令

在螢幕上印出

我們可以利用整數轉換指定(integral conversion specifier)來明確地將MATLAB中的雙倍浮點數轉成整數。例如將有正負號的32bit資料轉成16進位的格式:

See Also

fclose, ferror, fopen, fread, fscanf, fseek, ftell, fwrite, disp

References

[1] Kernighan, B.W. and D.M. Ritchie, The C Programming Language, Second Edition, Prentice-Hall, Inc., 1988.

[2] ANSI specification X3.159-1989: "Programming Language C," ANSI, 1430 Broadway, New York, NY 10018.


 fplot fprintf (serial)