Scroll to navigation

PRINTF(3) Manual del Programador de Linux PRINTF(3)

NOMBRE

printf, fprintf, dprintf, sprintf, snprintf, vprintf, vfprintf, vdprintf, vsprintf, vsnprintf - conversión de salida formateada

SINOPSIS

#include <stdio.h>
int printf(const char *format, ...);
int fprintf(FILE *stream, const char *format, ...);
int dprintf(int fd, const char *format, ...);
int sprintf(char *str, const char *format, ...);
int snprintf(char *str, size_t size, const char *format, ...);
#include <stdarg.h>
int vprintf(const char *format, va_list ap);
int vfprintf(FILE *stream, const char *format, va_list ap);
int vdprintf(int fd, const char *format, va_list ap);
int vsprintf(char *str, const char *format, va_list ap);
int vsnprintf(char *str, size_t size, const char *format, va_list ap);

Requisitos de Macros de Prueba de Características para glibc (véase feature_test_macros(7)):

snprintf(), vsnprintf():

_XOPEN_SOURCE >= 500 || _ISOC99_SOURCE ||
|| /* Glibc versions <= 2.19: */ _BSD_SOURCE

dprintf(), vdprintf():

_POSIX_C_SOURCE >= 200809L
_GNU_SOURCE

DESCRIPCIÓN

Las funciones de la familia printf() producen una salida de acuerdo a format como se describe abajo. Printf() y vprintf() escriben su salida a stdout, el flujo de salida estándar. fprintf() y vfprintf() escriben su salida al stream de salida dado. sprintf(), snprintf(), vsprintf() y vsnprintf() escriben a una cadena de caracteres str.

The function dprintf() is the same as fprintf() except that it outputs to a file descriptor, fd, instead of to a stdio stream.

The functions snprintf() and vsnprintf() write at most size bytes (including the terminating null byte ('\0')) to str.

The functions vprintf(), vfprintf(), vdprintf(), vsprintf(), vsnprintf() are equivalent to the functions printf(), fprintf(), dprintf(), sprintf(), snprintf(), respectively, except that they are called with a va_list instead of a variable number of arguments. These functions do not call the va_end macro. Because they invoke the va_arg macro, the value of ap is undefined after the call. See stdarg(3).

All of these functions write the output under the control of a format string that specifies how subsequent arguments (or arguments accessed via the variable-length argument facilities of stdarg(3)) are converted for output.

C99 and POSIX.1-2001 specify that the results are undefined if a call to sprintf(), snprintf(), vsprintf(), or vsnprintf() would cause copying to take place between objects that overlap (e.g., if the target string array and one of the supplied input arguments refer to the same buffer). See NOTES.

Formato de la cadena de formato

La cadena de formato es una cadena de caracteres que comienza y termina en su estado de cambios inicial, si lo hay. La cadena format está compuesta de cero o más directivas: caracteres ordinarios (no %) que se copian sin cambios al flujo de salida, e indicaciones de conversión, cada uno de las cuales produce la búsqueda de cero o más argumentos posteriores. Cada especificación de conversión se introduce mediante el carácter % y termina con un indicador de conversión. En medio puede haber (en este orden) cero o más opciones, una anchura de campo opcional mínima, una precisión opcional y un modificador de longitud opcional.

The arguments must correspond properly (after type promotion) with the conversion specifier. By default, the arguments are used in the order given, where each '*' (see Field width and Precision below) and each conversion specifier asks for the next argument (and it is an error if insufficiently many arguments are given). One can also specify explicitly which argument is taken, at each place where an argument is required, by writing "%m$" instead of '%' and "*m$" instead of '*', where the decimal integer m denotes the position in the argument list of the desired argument, indexed starting from 1. Thus,


printf("%*d", width, num);

y


printf("%2$*1$d", width, num);

son equivalentes. El segundo estilo permite referencias repetidas al mismo argumento. El estándar C99 no incluye el estilo usando caracteres '$', que proviene de `the Single UNIX Specification'. Si se utiliza el estilo con '$', debe ser usado para todas las conversiones tomando un argumento y todos los argumentos de anchura y precisión, pero puede mezclarse con formatos "%%" que no consumen ningún argumento. No puede haber huecos en los números de los argumentos especificados usando '$'; por ejemplo, si se especifican los argumentos 1 y 3, el argumento 2 debe ser también especificado en algún lugar en la cadena de formato.

Para alguna conversión numérica se usa un carácter radical ("punto decimal") o carácter separador de miles. El carácter real usado depende de la parte LC_NUMERIC de la localización. (Vea setlocale(3).) La localizacíon POSIX usa `.' como carácter radical y no posee un carácter separador de miles. Por tanto,


printf("%'.2f", 1234567.89);

produce "1234567.89" en la localización POSIX, "1234567,89" en la localización nl_NL, y "1.234.567,89" en la localización da_DK.

Caracteres de opción

El carácter % va seguido por cero o más de las siguientes opciones:

#
El valor debe ser convertido a un "formato alternativo". Para las conversiones o, el primer carácter de la cadena de salida se hace 0 (prefijando un cero si ya era distinto de cero). Para las conversiones x y X, la cadena "0x" (o "0X" para conversiones X) precede a los resultados que son distintos de 0. Para las conversiones a, A, e, E, f, F, g, y G, el resultado contendrá un punto decimal, aún si ningún dígito lo sigue (normalmente, sólo aparece un punto decimal en el resultado de aquellas conversiones que son seguidas de algún dígito). Para las conversiones g y G, en el resultado no se eliminan los ceros del final, como ocurriría en otro caso. Para otras conversiones, el resultado es indefinido.
0
El valor se debe rellenar con ceros. Para las conversiones d, i, o, u, x, X, a, A, e, E, f, F, g, y G , el valor convertido es rellenado a la izquierda con ceros en vez de blancos. Si las banderas 0 y - aparecen a la vez, la bandera 0 es ignorada. Si en una conversión numérica (d, i, o, u, x, y X), se indica una precisión, la bandera 0 se ignora. Para otras conversiones, el resultado es indefinido.
-
El valor convertido es justificado a la izquierda sobre el límite del campo. (Por defecto, la justificación es a la derecha). El valor convertido es rellenado a la derecha con blancos, en vez de a la izquierda con blancos o ceros. Un - sobreescribe un 0 si se indican ambos.
' '
(un espacio) Se debe dejar un espacio en blanco delante de un número positivo (o cadena vacía) producido por una conversión con signo.
+
A sign (+ or -) should always be placed before a number produced by a signed conversion. By default, a sign is used only for negative numbers. A + overrides a space if both are used.

The five flag characters above are defined in the C99 standard. The Single UNIX Specification specifies one further flag character.

'
For decimal conversion (i, d, u, f, F, g, G) the output is to be grouped with thousands' grouping characters if the locale information indicates any. (See setlocale(3).) Note that many versions of gcc(1) cannot parse this option and will issue a warning. (SUSv2 did not include %'F, but SUSv3 added it.)

glibc 2.2 añada un nuevo carácter de opción adicional.

For decimal integer conversion (i, d, u) the output uses the locale's alternative output digits, if any. For example, since glibc 2.2.3 this will give Arabic-Indic digits in the Persian ("fa_IR") locale.

Anchura de campo

Una cadena de dígitos decimales opcional (con un primer dígito distinto de cero) que especifica una anchura de campo mínimo. Si el valor convertido tiene menos caracteres que la anchura del campo, se rellenará con espacios a la izquierda (o a la derecha, si se da la opción de justificación a la izquierda). En lugar de una cadena de dígitos decimales se puede escribir "*" o "*m$" (para algún entero decimal m) para especificar que la anchura del campo se proporciona en el siguiente argumento o en el m-ésimo argumento, respectivamente, que debe ser de tipo int. Una anchura de campo negativa se toma como una opción `-' seguida por una anchura de campo positiva. En ningún caso, una anchura de campo inexistente o pequeña hace que el campo se trunque. Si el resultado de la conversión es más ancho que la anchura del campo, el campo se expande para contener el resultado de la conversión.

Precisión

An optional precision, in the form of a period ('.') followed by an optional decimal digit string. Instead of a decimal digit string one may write "*" or "*m$" (for some decimal integer m) to specify that the precision is given in the next argument, or in the m-th argument, respectively, which must be of type int. If the precision is given as just '.', the precision is taken to be zero. A negative precision is taken as if the precision were omitted. This gives the minimum number of digits to appear for d, i, o, u, x, and X conversions, the number of digits to appear after the radix character for a, A, e, E, f, and F conversions, the maximum number of significant digits for g and G conversions, or the maximum number of characters to be printed from a string for s and S conversions.

Indicador de longitud

Aquí, "conversión entera" significa una conversión d, i, o, u, x, o X.

La siguiente conversión entera se corresponde con un argumento signed char o unsigned char, o la siguiente conversión n se corresponde a un puntero a un argumento signed char.
La siguiente conversión entera se corresponde con un argumento short o unsigned short, o que la siguiente conversión n corresponde a un puntero a un argumento short.
(ele) La siguiente conversión entera corresponde a un argumento long o unsigned long, o que la siguiente conversión n corresponde a un puntero a un argumento long o que la siguiente conversión c corresponde a un argumento wint_t, o que la siguiente conversión s corresponde a un puntero a un argumento wchar_t.
(ele-ele). La siguiente conversión entera corresponde a un argumento long long o unsigned long long, o que la siguiente conversión n corresponde a un puntero a un argumento long long.
A synonym for ll. This is a nonstandard extension, derived from BSD; avoid its use in new code.
La siguiente conversión a, A, e, E, f, F, g, o G corresponde a un argumento long double. (C99 permite %LF, pero SUSv2 no.)
La siguiente conversión entera se corresponde con un argumento intmax_t o uintmax_t, o que la siguiente conversión n corresponde a un puntero a un argumento intmax_t.
La siguiente conversión entera se corresponde con un argumento size_t o ssize_t, o que la siguiente conversión n corresponde a un puntero a un argumento size_t.
A nonstandard synonym for z that predates the appearance of z. Do not use in new code.
La siguiente conversión entera se corresponde con un argumento ptrdiff_t, o que la siguiente conversión n corresponde a un puntero a un argumento ptrdiff_t.

SUSv3 specifies all of the above, except for those modifiers explicitly noted as being nonstandard extensions. SUSv2 specified only the length modifiers h (in hd, hi, ho, hx, hX, hn) and l (in ld, li, lo, lx, lX, ln, lc, ls) and L (in Le, LE, Lf, Lg, LG).

As a nonstandard extension, the GNU implementations treats ll and L as synonyms, so that one can, for example, write llg (as a synonym for the standards-compliant Lg) and Ld (as a synonym for the standards compliant lld). Such usage is nonportable.

Conversion specifiers

Un carácter que especifica el tipo de conversión a ser aplicado. Los indicadores de conversión y sus significados son:

El argumento int se convierte a la notación decimal con signo. La precisión, si la hay, da el número mínimo de dígitos que deben aparecer. Si el valor convertido necesita menos dígitos, se rellena a la izquierda con ceros. La precisión por omisión es 1. Cuando se imprime 0 con una precisión explícita 0, la salida es la cadena vacía.
El argumento unsigned int se convierte a un octal sin signo (o, a decimal sin signo (u, a a notación hexadecimal sin signo (x y X). Las letras abcdef son usadas para conversiones x. Las letras ABCDEF son usadas para conversiones X. La precisión, si se ha indicado alguna, da el mínimo número de dígitos que deben aparecer. Si el valor convertido requiere menos dígitos, éste es rellenado a la izquierda con ceros. La precisión por omisión es 1. Cuando se imprime 0 con una precisión explícita 0, la salida es la cadena vacía.
The double argument is rounded and converted in the style [-]d.ddde±dd where there is one digit (which is nonzero if the argument is nonzero) before the decimal-point character and the number of digits after it is equal to the precision; if the precision is missing, it is taken as 6; if the precision is zero, no decimal-point character appears. An E conversion uses the letter E (rather than e) to introduce the exponent. The exponent always contains at least two digits; if the value is zero, the exponent is 00.
El argumento double es redondeado y convertido a una notación decimal del estilo [-]ddd.ddd, donde el número de dígitos después del carácter del punto decimal es igual a la especificación de la precisión. Si no se indica precisión, ésta es tomada como 6. Si la precisión es explícitamente cero, no aparece el carácter del punto decimal. Si aparece un punto decimal, al menos aparece un dígito delante de él.
(SUSv2 does not know about F and says that character string representations for infinity and NaN may be made available. SUSv3 adds a specification for F. The C99 standard specifies "[-]inf" or "[-]infinity" for infinity, and a string starting with "nan" for NaN, in the case of f conversion, and "[-]INF" or "[-]INFINITY" or "NAN" in the case of F conversion.)
El argumento double es convertido al estilo de f o e (o F o E para conversiones G ). La precisión especifica el número de dígitos significativos. Si no se indica precisión, se dan 6 dígitos. Si la precisión es cero, ésta es tratada como 1. Se utiliza el formato de e si el exponente de su conversión es menor que -4 o más grande o igual a la precisión. Los ceros finales se eliminan de la parte fraccional del resultado. Un punto decimal sólo aparece si es seguido de al menos un dígito.
(C99; not in SUSv2, but added in SUSv3) For a conversion, the double argument is converted to hexadecimal notation (using the letters abcdef) in the style [-]0xh.hhhhp±d; for A conversion the prefix 0X, the letters ABCDEF, and the exponent separator P is used. There is one hexadecimal digit before the decimal point, and the number of digits after it is equal to the precision. The default precision suffices for an exact representation of the value if an exact representation in base 2 exists and otherwise is sufficiently large to distinguish values of type double. The digit before the decimal point is unspecified for nonnormalized numbers, and nonzero but otherwise unspecified for normalized numbers. The exponent always contains at least one digit; if the value is zero, the exponent is 0.
Si no está presente un modificador l, el argumento int es convertido a un unsigned char, y se escribe el carácter resultante. Si está presente un modificador l, el argumento wint_t (carácter ancho) se convierte a una secuencia multibyte llamando a la función wcrtomb(3), con un estado de conversión que comienza en el estado inicial, y se escribe la cadena multibyte resultante.
If no l modifier is present: the const char * argument is expected to be a pointer to an array of character type (pointer to a string). Characters from the array are written up to (but not including) a terminating null byte ('\0'); if a precision is specified, no more than the number specified are written. If a precision is given, no null byte need be present; if the precision is not specified, or is greater than the size of the array, the array must contain a terminating null byte.
Si está presente un modificador l: se espera que el argumento const wchar_t * sea un puntero a un vector de caracteres anchos. Los caracteres anchos del array se convierten a caracteres multibyte (cada uno llamando a la función wcrtomb(3), con un estado de conversión que comienza en el estado inicial antes del primer carácter ancho) incluyendo el carácter ancho nulo terminador. Los caracteres multibyte resultantes se escriben hasta llegar (pero sin incluir) el byte nulo terminador. Si se especifica una precisión, no se escriben más bytes de los indica el número, aunque no se escribe ningún carácter multibyte parcial. Advierta que la precisión determina el número de bytes escritos, no el número de caracteres anchos o posiciones de pantalla. El vector debe contener un carácter ancho nulo terminador, a menos que se de una precisión que sea tan pequeña que el número de bytes escritos la exceda antes de llegar al final del vector.
(No en C99 o C11, pero sí en SUSv2, SUSv3 y SUSv4.) Sinónimo de lc. No usar.
(No en C99 o C11, pero sí en SUSv2, SUSv3 y SUSv4.) Sinónimo de ls. No usar.
El argumento de tipo puntero void * se imprime en hexadecimal (como si se hubiera indicado %#x o %#lx).
The number of characters written so far is stored into the integer pointed to by the corresponding argument. That argument shall be an int *, or variant whose size matches the (optionally) supplied integer length modifier. No argument is converted. (This specifier is not supported by the bionic C library.) The behavior is undefined if the conversion specification includes any flags, a field width, or a precision.
(Glibc extension; supported by uClibc and musl.) Print output of strerror(errno). No argument is required.
%
Se escribe un `%'. No se convierte ningún argumento. La especificación completa de conversión es `%%'.

VALOR DEVUELTO

Upon successful return, these functions return the number of characters printed (excluding the null byte used to end output to strings).

The functions snprintf() and vsnprintf() do not write more than size bytes (including the terminating null byte ('\0')). If the output was truncated due to this limit, then the return value is the number of characters (excluding the terminating null byte) which would have been written to the final string if enough space had been available. Thus, a return value of size or more means that the output was truncated. (See also below under NOTES.)

If an output error is encountered, a negative value is returned.

ATRIBUTOS

Para obtener una explicación de los términos usados en esta sección, véase attributes(7).

Interfaz Atributo Valor
printf(), fprintf(), sprintf(), snprintf(), vprintf(), vfprintf(), vsprintf(), vsnprintf() Seguridad del hilo Configuración regional de multi-hilo seguro

CONFORME A

fprintf(), printf(), sprintf(), vprintf(), vfprintf(), vsprintf(): POSIX.1-2001, POSIX.1-2008, C89, C99.

snprintf(), vsnprintf(): POSIX.1-2001, POSIX.1-2008, C99.

The dprintf() and vdprintf() functions were originally GNU extensions that were later standardized in POSIX.1-2008.

Concerning the return value of snprintf(), SUSv2 and C99 contradict each other: when snprintf() is called with size=0 then SUSv2 stipulates an unspecified return value less than 1, while C99 allows str to be NULL in this case, and gives the return value (as always) as the number of characters that would have been written in case the output string has been large enough. POSIX.1-2001 and later align their specification of snprintf() with C99.

glibc 2.1 añade los modificadores de longitud hh, j, t y z y los caracteres de conversión a y A.

glibc 2.2 añade el carácter de conversión F con la semántica de C99, y el carácter de opción I.

NOTAS

Some programs imprudently rely on code such as the following


sprintf(buf, "%s some further text", buf);

to append text to buf. However, the standards explicitly note that the results are undefined if source and destination buffers overlap when calling sprintf(), snprintf(), vsprintf(), and vsnprintf(). Depending on the version of gcc(1) used, and the compiler options employed, calls such as the above will not produce the expected results.

La implementación de glibc de las funciones snprintf() y vsnprintf() es conforme con el estándar C99, es decir, se comporta como se describe arriba, desde la versión 2.1 de glibc. Hasta la versión 2.0.6 de glibc devolvían -1 cuando la salida era truncada.

ERRORES

Ya que sprintf() y vsprintf() asumen una cadena de longitud arbitraria, los invocadores deben tener cuidado de no sobrepasar el espacio real, lo que a menudo resulta imposible de garantizar. Advierta que las longitudes de las cadenas producidas dependen de la localización y que son difíciles de predecir. Use snprintf() y vsnprintf() en su lugar (o asprintf(3) y vasprintf(3)).

Fragmentos de código como printf(foo); indican a menudo un fallo, puesto que foo puede contener un carácter %. Si foo proviene de la entrada del usuario, puede contener %n, provocando que la llamada printf() escriba en memoria y creando un agujero de seguridad.

EJEMPLOS

Para imprimir Pi con cinco cifras decimales:


#include <math.h>
#include <stdio.h>
fprintf(stdout, "pi = %.5f\n", 4 * atan(1.0));

Para imprimir una fecha y una hora de la forma "Sunday, July 3, 10:02", donde weekday y month son punteros a cadenas:


#include <stdio.h>
fprintf(stdout, "%s, %s %d, %.2d:%.2d\n",

weekday, month, day, hour, min);

Muchos países usan el orden día-mes-año. Por tanto, una versión internacionalizada debe ser capaz de mostrar los argumentos en el orden indicado por el formato:


#include <stdio.h>
fprintf(stdout, formato,

diasemana, mes, día, hora, min);

donde formato depende de la localización y puede permutar los argumentos. Con el valor


"%1$s, %3$d. %2$s, %4$d:%5$.2d\n"

se podría obtener "Sonntag, 3. Juli, 10:02".

Para reservar una cadena de 128 bytes e imprimir dentro de ella: Para reservar una cadena suficientemente grande e imprimir dentro de ella: (código correcto tanto para glibc 2.0 como glibc 2.1):

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
char *
make_message(const char *fmt, ...)
{

int n = 0;
size_t size = 0;
char *p = NULL;
va_list ap;
/* Determine required size */
va_start(ap, fmt);
n = vsnprintf(p, size, fmt, ap);
va_end(ap);
if (n < 0)
return NULL;
/* One extra byte for '\0' */
size = (size_t) n + 1;
p = malloc(size);
if (p == NULL)
return NULL;
va_start(ap, fmt);
n = vsnprintf(p, size, fmt, ap);
va_end(ap);
if (n < 0) {
free(p);
return NULL;
}
return p; }

If truncation occurs in glibc versions prior to 2.0.6, this is treated as an error instead of being handled gracefully.

VÉASE TAMBIÉN

printf(1), asprintf(3), puts(3), scanf(3), setlocale(3), strfromd(3), wcrtomb(3), wprintf(3), locale(5)

COLOFÓN

Esta página es parte de la versión 5.10 del proyecto Linux man-pages. Puede encontrar una descripción del proyecto, información sobre cómo informar errores y la última versión de esta página en https://www.kernel.org/doc/man-pages/.

TRADUCCIÓN

La traducción al español de esta página del manual fue creada por Sebastian Desimone <chipy@argenet.com.ar>, juanma <imontalvoo@medynet.com>, Juan Piernas <piernas@ditec.um.es> y Miguel Pérez Ibars <mpi79470@alu.um.es>

Esta traducción es documentación libre; lea la GNU General Public License Version 3 o posterior con respecto a las condiciones de copyright. No existe NINGUNA RESPONSABILIDAD.

Si encuentra algún error en la traducción de esta página del manual, envíe un correo electrónico a debian-l10n-spanish@lists.debian.org.

1 Noviembre 2020 GNU