Main Content

fprintf

Write data to text file

Description

example

fprintf(fileID,formatSpec,A1,...,An)applies theformatSpecto all elements of arraysA1,...Anin column order, and writes the data to a text file.fprintfuses the encoding scheme specified in the call tofopen.

example

fprintf(formatSpec,A1,...,An)formats data and displays the results on the screen.

example

nbytes= fprintf(___)returns the number of bytes thatfprintf写道,在公关使用任何输入参数eceding syntaxes.

Examples

collapse all

Print multiple numeric values and literal text to the screen.

A1 = [9.9, 9900]; A2 = [8.8, 7.7 ;...8800, 7700]; formatSpec ='X is %4.2f meters or %8.3f mm\n'; fprintf(formatSpec,A1,A2)
X is 9.90 meters or 9900.000 mm X is 8.80 meters or 8800.000 mm X is 7.70 meters or 7700.000 mm

%4.2fin theformatSpecinput specifies that the first value in each line of output is a floating-point number with a field width of four digits, including two digits after the decimal point.%8.3fin theformatSpecinput specifies that the second value in each line of output is a floating-point number with a field width of eight digits, including three digits after the decimal point.\nis a control character that starts a new line.

Explicitly convert double-precision values with fractions to integer values.

a = [1.02 3.04 5.06]; fprintf('%d\n',round(a));
1 3 5

%din theformatSpecinput prints each value in the vector,round(a), as a signed integer.\nis a control character that starts a new line.

Write a short table of the exponential function to a text file calledexp.txt.

x = 0:.1:1; A = [x; exp(x)]; fileID = fopen('exp.txt','w'); fprintf(fileID,'%6s %12s\n','x',“exp (x)”); fprintf(fileID,'%6.2f %12.8f\n',A); fclose(fileID);

The first call tofprintfprints header textxandexp(x), and the second call prints the values from variableA.

If you plan to read the file withMicrosoft®Notepad, use'\r\n'instead of'\n'to move to a new line. For example, replace the calls tofprintfwith the following:

fprintf(fileID,'%6s %12s\r\n','x',“exp (x)”); fprintf(fileID,'%6.2f %12.8f\r\n',A);

MATLAB®import functions, all UNIX®applications, andMicrosoft Wordand WordPad recognize'\n'as a newline indicator.

查看文件的内容typecommand.

typeexp.txt
x exp(x) 0.00 1.00000000 0.10 1.10517092 0.20 1.22140276 0.30 1.34985881 0.40 1.49182470 0.50 1.64872127 0.60 1.82211880 0.70 2.01375271 0.80 2.22554093 0.90 2.45960311 1.00 2.71828183

Write data to a file and return the number of bytes written.

Write an array of data,A, to a file and get the number of bytes thatfprintfwrites.

A = magic(4); fileID = fopen('myfile.txt','w'); nbytes = fprintf(fileID,'%5d %5d %5d %5d\n',A)
nbytes = 96

Thefprintffunction wrote 96 bytes to the file.

Close the file.

fclose(fileID);

查看文件的内容typecommand.

type('myfile.txt')
16 5 9 4 2 11 7 14 3 10 6 15 13 8 12 1

Display a hyperlink (The MathWorks Web Site) on the screen.

url ='//www.tianjin-qmedu.com'; sitename ='The MathWorks Web Site'; fprintf('%s\n',url,sitename)

%sin theformatSpecinput indicates that the values of the variablesurlandsitename, should be printed as text.

Input Arguments

collapse all

File identifier, specified as one of the following:

  • A file identifier obtained fromfopen.

  • 1for standard output (the screen).

  • 2for standard error.

Data Types:double

格式of the output fields, specified using formatting operators.formatSpecalso can include ordinary text and special characters.

IfformatSpecincludes literal text representing escape characters, such as\n, thenfprintftranslates the escape characters.

formatSpeccan be a character vector in single quotes, or a string scalar.

格式化Operator

A formatting operator starts with a percent sign,%, and ends with a conversion character. The conversion character is required. Optionally, you can specify identifier, flags, field width, precision, and subtype operators between%and the conversion character. (Spaces are invalid between operators and are shown here only for readability).

Schematic of formatting operator characters.

Conversion Character

This table shows conversion characters to format numeric and character data as text.

Value Type Conversion Details

Integer, signed

%dor%i

Base 10

Integer, unsigned

%u

Base 10

%o

Base 8 (octal)

%x

Base 16 (hexadecimal), lowercase lettersaf

%X

Same as%x, uppercase lettersAF

Floating-point number

%f

Fixed-point notation (Use a precision operator to specify the number of digits after the decimal point.)

%e

Exponential notation, such as3.141593e+00(Use a precision operator to specify the number of digits after the decimal point.)

%E

Same as%e, but uppercase, such as3.141593E+00(Use a precision operator to specify the number of digits after the decimal point.)

%g

The more compact of%eor%f, with no trailing zeros (Use a precision operator to specify the number of significant digits.)

%G

The more compact of%Eor%f, with no trailing zeros (Use a precision operator to specify the number of significant digits.)

Characters or strings

%c

Single character

%s

Character vector or string array. The type of the output text is the same as the type offormatSpec.

Optional Operators

The optional identifier, flags, field width, precision, and subtype operators further define the format of the output text.

  • Identifier

    Order for processing the function input arguments. Use the syntaxn$, wherenrepresents the positions of the other input arguments in the function call.

    Example:('%3$s %2$s %1$s %2$s','A','B','C')prints input arguments'A','B','C'as follows:C B A B.

    Note:If an input argument is an array, you cannot use identifiers to specify particular array elements from that input argument.

  • Flags

    '–'

    Left-justify.
    Example:%-5.2f
    Example:%-10s

    '+'

    Always print a sign character (+ or –) for any numeric value.
    Example:%+5.2f
    Right-justify text.
    Example:%+10s

    ' '

    Insert a space before the value.
    Example:% 5.2f

    '0'

    Pad to field width with zeros before the value.
    Example:%05.2f

    '#'

    Modify selected numeric conversions:

    • For%o,%x, or%X, print0,0x, or0Xprefix.

    • For%f,%e, or%E, print decimal point even when precision is 0.

    • For%gor%G, do not remove trailing zeros or decimal point.

    Example:%#5.0f

  • Field Width

    Minimum number of characters to print. The field width operator can be a number, or an asterisk (*) to refer to an input argument.

    When you specify*as the field width operator, the other input arguments must provide both a width and a value to be printed. Widths and values can be pairs of arguments or pairs within a numeric array. With*as the field width operator, you can print different values with different widths.

    Example:The input arguments('%12d',intmax)are equivalent to('%*d',12,intmax).

    Example:The input arguments('%*d',[2 10 5 100])return'10 100', with two spaces allocated for10and five spaces for100. As an alternative, you also can specify the field widths and values as multiple arguments, as in('%*d',2,10,5,100).

    The function pads to field width with spaces before the value unless otherwise specified by flags.

  • Precision

    For%f,%e, or%E

    Number of digits to the right of the decimal point
    Example:'%.4f'printspias'3.1416'

    For%gor%G

    Number of significant digits
    Example:'%.4g'printspias'3.142'

    The precision operator can be a number, or an asterisk (*) to refer to an argument.

    When you specify*as the field precision operator, the other input arguments must provide both a precision and a value to be printed. Precisions and values can be pairs of arguments, or pairs within a numeric array. With*as the precision operator, you can print different values to different precisions.

    When you specify*.*as field width and precision operators, you must specify field widths, precisions, and values as triplets.

    Example:The input arguments('%.4f',pi)are equivalent to('%.*f',4,pi).

    Example:The input arguments('%6.4f',pi)are equivalent to('%*.*f',6,4,pi).

    Example:The input arguments('%*.*f',6,4,pi,9,6,exp(1))return'3.1416 2.718282', with9and6as the field width and precision for the output ofexp(1).

    Note

    If you specify a precision operator for floating-point values that exceeds the precision of the input numeric data type, the results might not match the input values to the precision you specified. The result depends on your computer hardware and operating system.

  • Subtypes

    You can use a subtype operator to print a floating-point value as its octal, decimal, or hexadecimal value. The subtype operator immediately precedes the conversion character. This table shows the conversions that can use subtypes.

    Input Value Type

    Subtype and Conversion Character

    Output Value Type

    Floating-point number

    %bxor%bX
    %bo
    %bu

    Double-precision hexadecimal, octal, or decimal value
    Example:%bxprintspias400921fb54442d18

    %txor%tX
    %to
    %tu

    Single-precision hexadecimal, octal, or decimal value
    Example:%txprintspias40490fdb

Text Before or After Formatting Operators

formatSpeccan also include additional text before a percent sign,%, or after a conversion character. The text can be:

  • Ordinary text to print.

  • Special characters that you cannot enter as ordinary text. This table shows how to represent special characters informatSpec.

    Special Character

    Representation

    Single quotation mark

    ''

    Percent character

    %%

    Backslash

    \\

    Alarm

    \a

    Backspace

    \b

    Form feed

    \f

    New line

    \n

    Carriage return

    \r

    Horizontal tab

    \t

    Vertical tab

    \v

    Character whose Unicode®numeric value can be represented by the hexadecimal number,N

    \xN

    Example:fprintf('\x5A')returns'Z'

    Character whose Unicode numeric value can be represented by the octal number,N

    \N

    Example:fprintf('\132')returns'Z'

Notable Behavior of Conversions with Formatting Operators

  • Numeric conversions print only the real component of complex numbers.

  • If you specify a conversion that does not fit the data, such as a text conversion for a numeric value, MATLAB overrides the specified conversion, and uses%e.

    Example:'%s'convertspito3.141593e+00.

  • If you apply a text conversion (either%cor%s) to integer values, MATLAB converts values that correspond to valid character codes to characters.

    Example:'%s'converts[65 66 67]toABC.

Numeric or character arrays, specified as a scalar, vector, matrix, or multidimensional array.

Data Types:single|double|int8|int16|int32|int64|uint8|uint16|uint32|uint64|logical|char

Output Arguments

collapse all

Number of bytes thatfprintfwrites, returned as a scalar. When writing to a file,nbytesis determined by the character encoding. When printing data to the screen,nbytesis the number of characters displayed on the screen.

Tips

  • 格式specifiers for the reading functionssscanfandfscanfdiffer from the formats for the writing functionssprintfandfprintf. The reading functions do not support a precision field. The width field specifies a minimum for writing, but a maximum for reading.

  • If you specify an invalid formatting operator or special character, thenfprintfprints all text up to the invalid operator or character and discards the rest.

    Example:IfformatSpecis'value = %z', thenfprintfprints'value ='because%zis not a formatting operator.

    Example:IfformatSpecis'character \x99999 = %s', thenfprintfprints'character'because\x99999is not a valid special character.

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.

Extended Capabilities

Version History

Introduced before R2006a