.\" -*- coding: UTF-8 -*- .\" Copyright (c) 1999 Andries Brouwer (aeb@cwi.nl) .\" .\" Earlier versions of this page influenced the present text. .\" It was derived from a Berkeley page with version .\" @(#)printf.3 6.14 (Berkeley) 7/30/91 .\" converted for Linux by faith@cs.unc.edu, updated by .\" Helmut.Geyer@iwr.uni-heidelberg.de, agulbra@troll.no and Bruno Haible. .\" .\" %%%LICENSE_START(GPLv2+_DOC_FULL) .\" This is free documentation; you can redistribute it and/or .\" modify it under the terms of the GNU General Public License as .\" published by the Free Software Foundation; either version 2 of .\" the License, or (at your option) any later version. .\" .\" The GNU General Public License's references to "object code" .\" and "executables" are to be interpreted as the output of any .\" document formatting or typesetting system, including .\" intermediate and printed output. .\" .\" This manual is distributed in the hope that it will be useful, .\" but WITHOUT ANY WARRANTY; without even the implied warranty of .\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the .\" GNU General Public License for more details. .\" .\" You should have received a copy of the GNU General Public .\" License along with this manual; if not, see .\" . .\" %%%LICENSE_END .\" .\" 1999-11-25 aeb - Rewritten, using SUSv2 and C99. .\" 2000-07-26 jsm28@hermes.cam.ac.uk - three small fixes .\" 2000-10-16 jsm28@hermes.cam.ac.uk - more fixes .\" .\"******************************************************************* .\" .\" This file was generated with po4a. Translate the source file. .\" .\"******************************************************************* .TH PRINTF 3 "1 Noviembre 2020" GNU "Manual del Programador de Linux" .SH NOMBRE printf, fprintf, dprintf, sprintf, snprintf, vprintf, vfprintf, vdprintf, vsprintf, vsnprintf \- conversión de salida formateada .SH SINOPSIS .nf \fB#include \fP .PP \fBint printf(const char *\fP\fIformat\fP\fB, ...);\fP \fBint fprintf(FILE *\fP\fIstream\fP\fB, const char *\fP\fIformat\fP\fB, ...);\fP \fBint dprintf(int \fP\fIfd\fP\fB, const char *\fP\fIformat\fP\fB, ...);\fP \fBint sprintf(char *\fP\fIstr\fP\fB, const char *\fP\fIformat\fP\fB, ...);\fP \fBint snprintf(char *\fP\fIstr\fP\fB, size_t \fP\fIsize\fP\fB, const char *\fP\fIformat\fP\fB, ...);\fP \fB#include \fP .PP \fBint vprintf(const char *\fP\fIformat\fP\fB, va_list \fP\fIap\fP\fB);\fP \fBint vfprintf(FILE *\fP\fIstream\fP\fB, const char *\fP\fIformat\fP\fB, va_list \fP\fIap\fP\fB);\fP \fBint vdprintf(int \fP\fIfd\fP\fB, const char *\fP\fIformat\fP\fB, va_list \fP\fIap\fP\fB);\fP \fBint vsprintf(char *\fP\fIstr\fP\fB, const char *\fP\fIformat\fP\fB, va_list \fP\fIap\fP\fB);\fP \fBint vsnprintf(char *\fP\fIstr\fP\fB, size_t \fP\fIsize\fP\fB, const char *\fP\fIformat\fP\fB, va_list \fP\fIap\fP\fB);\fP .fi .PP .RS -4 Requisitos de Macros de Prueba de Características para glibc (véase \fBfeature_test_macros\fP(7)): .RE .PP .ad l \fBsnprintf\fP(), \fBvsnprintf\fP(): .RS 4 _XOPEN_SOURCE\ >=\ 500 || _ISOC99_SOURCE || || /* Glibc versions <= 2.19: */ _BSD_SOURCE .RE .PP \fBdprintf\fP(), \fBvdprintf\fP(): .PD 0 .RS 4 .TP 4 Desde glibc 2.10: _POSIX_C_SOURCE\ >=\ 200809L .TP Antes de glibc 2.10: _GNU_SOURCE .RE .ad .PD .SH DESCRIPCIÓN Las funciones de la familia \fBprintf\fP() producen una salida de acuerdo a \fIformat\fP como se describe abajo. \fBPrintf\fP() y \fBvprintf\fP() escriben su salida a \fIstdout\fP, el flujo de salida estándar. \fBfprintf\fP() y \fBvfprintf\fP() escriben su salida al \fIstream\fP de salida dado. \fBsprintf\fP(), \fBsnprintf\fP(), \fBvsprintf\fP() y \fBvsnprintf\fP() escriben a una cadena de caracteres \fIstr\fP. .PP The function \fBdprintf\fP() is the same as \fBfprintf\fP() except that it outputs to a file descriptor, \fIfd\fP, instead of to a \fIstdio\fP stream. .PP The functions \fBsnprintf\fP() and \fBvsnprintf\fP() write at most \fIsize\fP bytes (including the terminating null byte (\(aq\e0\(aq)) to \fIstr\fP. .PP The functions \fBvprintf\fP(), \fBvfprintf\fP(), \fBvdprintf\fP(), \fBvsprintf\fP(), \fBvsnprintf\fP() are equivalent to the functions \fBprintf\fP(), \fBfprintf\fP(), \fBdprintf\fP(), \fBsprintf\fP(), \fBsnprintf\fP(), respectively, except that they are called with a \fIva_list\fP instead of a variable number of arguments. These functions do not call the \fIva_end\fP macro. Because they invoke the \fIva_arg\fP macro, the value of \fIap\fP is undefined after the call. See \fBstdarg\fP(3). .PP All of these functions write the output under the control of a \fIformat\fP string that specifies how subsequent arguments (or arguments accessed via the variable\-length argument facilities of \fBstdarg\fP(3)) are converted for output. .PP C99 and POSIX.1\-2001 specify that the results are undefined if a call to \fBsprintf\fP(), \fBsnprintf\fP(), \fBvsprintf\fP(), or \fBvsnprintf\fP() 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. .SS "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 \fBformat\fP está compuesta de cero o más directivas: caracteres ordinarios (no \fB%\fP) 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 \fB%\fP y termina con un \fIindicador de conversión\fP. En medio puede haber (en este orden) cero o más \fIopciones\fP, una \fIanchura de campo\fP opcional mínima, una \fIprecisión\fP opcional y un \fImodificador de longitud\fP opcional. .PP The arguments must correspond properly (after type promotion) with the conversion specifier. By default, the arguments are used in the order given, where each \(aq*\(aq (see \fIField width\fP and \fIPrecision\fP 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 \(aq%\(aq and "*m$" instead of \(aq*\(aq, where the decimal integer \fIm\fP denotes the position in the argument list of the desired argument, indexed starting from 1. Thus, .PP .in +4n .EX printf("%*d", width, num); .EE .in .PP y .PP .in +4n .EX printf("%2$*1$d", width, num); .EE .in .PP son equivalentes. El segundo estilo permite referencias repetidas al mismo argumento. El estándar C99 no incluye el estilo usando caracteres \(aq$\(aq, que proviene de `the Single UNIX Specification'. Si se utiliza el estilo con \(aq$\(aq, 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 \(aq$\(aq; 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. .PP 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 \fBLC_NUMERIC\fP de la localización. (Vea \fBsetlocale\fP(3).) La localizacíon POSIX usa `.' como carácter radical y no posee un carácter separador de miles. Por tanto, .PP .in +4n .EX printf("%\(aq.2f", 1234567.89); .EE .in .PP 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. .SS "Caracteres de opción" El carácter % va seguido por cero o más de las siguientes opciones: .TP \fB#\fP El valor debe ser convertido a un "formato alternativo". Para las conversiones \fBo\fP, el primer carácter de la cadena de salida se hace 0 (prefijando un cero si ya era distinto de cero). Para las conversiones \fBx\fP y \fBX\fP, la cadena "0x" (o "0X" para conversiones \fBX\fP) precede a los resultados que son distintos de 0. Para las conversiones \fBa\fP, \fBA\fP, \fBe\fP, \fBE\fP, \fBf\fP, \fBF\fP, \fBg\fP, y \fBG\fP, 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 \fBg\fP y \fBG\fP, en el resultado no se eliminan los ceros del final, como ocurriría en otro caso. Para otras conversiones, el resultado es indefinido. .TP \fB\&0\fP El valor se debe rellenar con ceros. Para las conversiones \fBd\fP, \fBi\fP, \fBo\fP, \fBu\fP, \fBx\fP, \fBX\fP, \fBa\fP, \fBA\fP, \fBe\fP, \fBE\fP, \fBf\fP, \fBF\fP, \fBg\fP, y \fBG\fP , el valor convertido es rellenado a la izquierda con ceros en vez de blancos. Si las banderas \fB\&0\fP y \fB\-\fP aparecen a la vez, la bandera \fB\&0\fP es ignorada. Si en una conversión numérica (\fBd\fP, \fBi\fP, \fBo\fP, \fBu\fP, \fBx\fP, y \fBX\fP), se indica una precisión, la bandera \fB\&0\fP se ignora. Para otras conversiones, el resultado es indefinido. .TP \fB\-\fP 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 \fB\-\fP sobreescribe un \fB\&0\fP si se indican ambos. .TP \fB\(aq \(aq\fP (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. .TP \fB+\fP 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 \fB+\fP overrides a space if both are used. .PP The five flag characters above are defined in the C99 standard. The Single UNIX Specification specifies one further flag character. .TP \fB\(aq\fP For decimal conversion (\fBi\fP, \fBd\fP, \fBu\fP, \fBf\fP, \fBF\fP, \fBg\fP, \fBG\fP) the output is to be grouped with thousands' grouping characters if the locale information indicates any. (See \fBsetlocale\fP(3).) Note that many versions of \fBgcc\fP(1) cannot parse this option and will issue a warning. (SUSv2 did not include \fI%\(aqF\fP, but SUSv3 added it.) .PP glibc 2.2 añada un nuevo carácter de opción adicional. .TP \fBI\fP .\" outdigits keyword in locale file For decimal integer conversion (\fBi\fP, \fBd\fP, \fBu\fP) 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. .SS "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 \fIm\fP) para especificar que la anchura del campo se proporciona en el siguiente argumento o en el \fIm\fP\-ésimo argumento, respectivamente, que debe ser de tipo \fIint\fP. 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. .SS Precisión An optional precision, in the form of a period (\(aq.\(aq) followed by an optional decimal digit string. Instead of a decimal digit string one may write "*" or "*m$" (for some decimal integer \fIm\fP) to specify that the precision is given in the next argument, or in the \fIm\fP\-th argument, respectively, which must be of type \fIint\fP. If the precision is given as just \(aq.\(aq, 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 \fBd\fP, \fBi\fP, \fBo\fP, \fBu\fP, \fBx\fP, and \fBX\fP conversions, the number of digits to appear after the radix character for \fBa\fP, \fBA\fP, \fBe\fP, \fBE\fP, \fBf\fP, and \fBF\fP conversions, the maximum number of significant digits for \fBg\fP and \fBG\fP conversions, or the maximum number of characters to be printed from a string for \fBs\fP and \fBS\fP conversions. .SS "Indicador de longitud" Aquí, "conversión entera" significa una conversión \fBd\fP, \fBi\fP, \fBo\fP, \fBu\fP, \fBx\fP, o \fBX\fP. .TP \fBhh\fP La siguiente conversión entera se corresponde con un argumento \fIsigned char\fP o \fIunsigned char\fP, o la siguiente conversión \fBn\fP se corresponde a un puntero a un argumento \fIsigned char\fP. .TP \fBh\fP La siguiente conversión entera se corresponde con un argumento \fIshort\fP o \fIunsigned short\fP, o que la siguiente conversión \fBn\fP corresponde a un puntero a un argumento \fIshort\fP. .TP \fBl\fP (ele) La siguiente conversión entera corresponde a un argumento \fIlong\fP o \fIunsigned long\fP, o que la siguiente conversión \fBn\fP corresponde a un puntero a un argumento \fIlong\fP o que la siguiente conversión \fBc\fP corresponde a un argumento \fIwint_t\fP, o que la siguiente conversión \fBs\fP corresponde a un puntero a un argumento \fIwchar_t\fP. .TP \fBll\fP (ele\-ele). La siguiente conversión entera corresponde a un argumento \fIlong long\fP o \fIunsigned long long,\fP o que la siguiente conversión \fBn\fP corresponde a un puntero a un argumento \fIlong long\fP. .TP \fBq\fP A synonym for \fBll\fP. This is a nonstandard extension, derived from BSD; avoid its use in new code. .TP \fBL\fP La siguiente conversión \fBa\fP, \fBA\fP, \fBe\fP, \fBE\fP, \fBf\fP, \fBF\fP, \fBg\fP, o \fBG\fP corresponde a un argumento \fIlong double\fP. (C99 permite %LF, pero SUSv2 no.) .TP \fBj\fP La siguiente conversión entera se corresponde con un argumento \fIintmax_t\fP o \fIuintmax_t\fP, o que la siguiente conversión \fBn\fP corresponde a un puntero a un argumento \fIintmax_t\fP. .TP \fBz\fP La siguiente conversión entera se corresponde con un argumento \fIsize_t\fP o \fIssize_t\fP, o que la siguiente conversión \fBn\fP corresponde a un puntero a un argumento \fIsize_t\fP. .TP \fBZ\fP A nonstandard synonym for \fBz\fP that predates the appearance of \fBz\fP. Do not use in new code. .TP \fBt\fP La siguiente conversión entera se corresponde con un argumento \fIptrdiff_t\fP, o que la siguiente conversión \fBn\fP corresponde a un puntero a un argumento \fIptrdiff_t\fP. .PP SUSv3 specifies all of the above, except for those modifiers explicitly noted as being nonstandard extensions. SUSv2 specified only the length modifiers \fBh\fP (in \fBhd\fP, \fBhi\fP, \fBho\fP, \fBhx\fP, \fBhX\fP, \fBhn\fP) and \fBl\fP (in \fBld\fP, \fBli\fP, \fBlo\fP, \fBlx\fP, \fBlX\fP, \fBln\fP, \fBlc\fP, \fBls\fP) and \fBL\fP (in \fBLe\fP, \fBLE\fP, \fBLf\fP, \fBLg\fP, \fBLG\fP). .PP .\" As a nonstandard extension, the GNU implementations treats \fBll\fP and \fBL\fP as synonyms, so that one can, for example, write \fBllg\fP (as a synonym for the standards\-compliant \fBLg\fP) and \fBLd\fP (as a synonym for the standards compliant \fBlld\fP). Such usage is nonportable. .SS "Conversion specifiers" Un carácter que especifica el tipo de conversión a ser aplicado. Los indicadores de conversión y sus significados son: .TP \fBd\fP, \fBi\fP El argumento \fIint\fP 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. .TP \fBo\fP, \fBu\fP, \fBx\fP, \fBX\fP El argumento \fIunsigned int\fP se convierte a un octal sin signo (\fBo\fP, a decimal sin signo (\fBu\fP, a a notación hexadecimal sin signo (\fBx\fP y \fBX\fP). Las letras \fBabcdef\fP son usadas para conversiones \fBx\fP. Las letras \fBABCDEF\fP son usadas para conversiones \fBX\fP. 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. .TP \fBe\fP, \fBE\fP The \fIdouble\fP argument is rounded and converted in the style [\-]d\fB\&.\fPddd\fBe\fP\(+-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 \fBE\fP conversion uses the letter \fBE\fP (rather than \fBe\fP) to introduce the exponent. The exponent always contains at least two digits; if the value is zero, the exponent is 00. .TP \fBf\fP, \fBF\fP El argumento \fIdouble\fP es redondeado y convertido a una notación decimal del estilo [\-]ddd\fB\&.\fPddd, 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. .IP (SUSv2 does not know about \fBF\fP and says that character string representations for infinity and NaN may be made available. SUSv3 adds a specification for \fBF\fP. The C99 standard specifies "[\-]inf" or "[\-]infinity" for infinity, and a string starting with "nan" for NaN, in the case of \fBf\fP conversion, and "[\-]INF" or "[\-]INFINITY" or "NAN" in the case of \fBF\fP conversion.) .TP \fBg\fP, \fBG\fP El argumento \fIdouble\fP es convertido al estilo de \fBf\fP o \fBe\fP (o \fBF\fP o \fBE\fP para conversiones \fBG\fP ). 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 \fBe\fP 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. .TP \fBa\fP, \fBA\fP (C99; not in SUSv2, but added in SUSv3) For \fBa\fP conversion, the \fIdouble\fP argument is converted to hexadecimal notation (using the letters abcdef) in the style [\-]\fB0x\fPh\fB\&.\fPhhhh\fBp\fP\(+-d; for \fBA\fP conversion the prefix \fB0X\fP, the letters ABCDEF, and the exponent separator \fBP\fP 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 \fIdouble\fP. 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. .TP \fBc\fP Si no está presente un modificador \fBl\fP, el argumento \fIint\fP es convertido a un \fIunsigned char\fP, y se escribe el carácter resultante. Si está presente un modificador \fBl\fP, el argumento \fIwint_t\fP (carácter ancho) se convierte a una secuencia multibyte llamando a la función \fBwcrtomb\fP(3), con un estado de conversión que comienza en el estado inicial, y se escribe la cadena multibyte resultante. .TP \fBs\fP If no \fBl\fP modifier is present: the \fIconst char\ *\fP 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 (\(aq\e0\(aq); 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. .IP Si está presente un modificador \fBl\fP: se espera que el argumento \fIconst wchar_t\ *\fP 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 \fBwcrtomb\fP(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 \fIbytes\fP escritos, no el número de \fIcaracteres anchos\fP o \fIposiciones de pantalla\fP. 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. .TP \fBC\fP (No en C99 o C11, pero sí en SUSv2, SUSv3 y SUSv4.) Sinónimo de \fBlc\fP. No usar. .TP \fBS\fP (No en C99 o C11, pero sí en SUSv2, SUSv3 y SUSv4.) Sinónimo de \fBls\fP. No usar. .TP \fBp\fP El argumento de tipo puntero \fIvoid\ *\fP se imprime en hexadecimal (como si se hubiera indicado \fB%#x\fP o \fB%#lx\fP). .TP \fBn\fP The number of characters written so far is stored into the integer pointed to by the corresponding argument. That argument shall be an \fIint\ *\fP, 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. .TP \fBm\fP (Glibc extension; supported by uClibc and musl.) Print output of \fIstrerror(errno)\fP. No argument is required. .TP \fB%\fP Se escribe un `%'. No se convierte ningún argumento. La especificación completa de conversión es `%%'. .SH "VALOR DEVUELTO" Upon successful return, these functions return the number of characters printed (excluding the null byte used to end output to strings). .PP The functions \fBsnprintf\fP() and \fBvsnprintf\fP() do not write more than \fIsize\fP bytes (including the terminating null byte (\(aq\e0\(aq)). 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 \fIsize\fP or more means that the output was truncated. (See also below under NOTES.) .PP If an output error is encountered, a negative value is returned. .SH ATRIBUTOS Para obtener una explicación de los términos usados en esta sección, véase \fBattributes\fP(7). .TS allbox; lbw23 lb lb l l l. Interfaz Atributo Valor T{ \fBprintf\fP(), \fBfprintf\fP(), .br \fBsprintf\fP(), \fBsnprintf\fP(), .br \fBvprintf\fP(), \fBvfprintf\fP(), .br \fBvsprintf\fP(), \fBvsnprintf\fP() T} Seguridad del hilo Configuración regional de multi\-hilo seguro .TE .sp 1 .SH "CONFORME A" \fBfprintf\fP(), \fBprintf\fP(), \fBsprintf\fP(), \fBvprintf\fP(), \fBvfprintf\fP(), \fBvsprintf\fP(): POSIX.1\-2001, POSIX.1\-2008, C89, C99. .PP \fBsnprintf\fP(), \fBvsnprintf\fP(): POSIX.1\-2001, POSIX.1\-2008, C99. .PP The \fBdprintf\fP() and \fBvdprintf\fP() functions were originally GNU extensions that were later standardized in POSIX.1\-2008. .PP .\" .PP .\" Linux libc4 knows about the five C standard flags. .\" It knows about the length modifiers \fBh\fP, \fBl\fP, \fBL\fP, .\" and the conversions .\" \fBc\fP, \fBd\fP, \fBe\fP, \fBE\fP, \fBf\fP, \fBF\fP, .\" \fBg\fP, \fBG\fP, \fBi\fP, \fBn\fP, \fBo\fP, \fBp\fP, .\" \fBs\fP, \fBu\fP, \fBx\fP, and \fBX\fP, .\" where \fBF\fP is a synonym for \fBf\fP. .\" Additionally, it accepts \fBD\fP, \fBO\fP, and \fBU\fP as synonyms .\" for \fBld\fP, \fBlo\fP, and \fBlu\fP. .\" (This is bad, and caused serious bugs later, when .\" support for \fB%D\fP disappeared.) .\" No locale-dependent radix character, .\" no thousands' separator, no NaN or infinity, no "%m$" and "*m$". .\" .PP .\" Linux libc5 knows about the five C standard flags and the \(aq flag, .\" locale, "%m$" and "*m$". .\" It knows about the length modifiers \fBh\fP, \fBl\fP, \fBL\fP, .\" \fBZ\fP, and \fBq\fP, but accepts \fBL\fP and \fBq\fP .\" both for \fIlong double\fP and for \fIlong long\fP (this is a bug). .\" It no longer recognizes \fBF\fP, \fBD\fP, \fBO\fP, and \fBU\fP, .\" but adds the conversion character .\" .BR m , .\" which outputs .\" .IR strerror(errno) . .\" .PP .\" glibc 2.0 adds conversion characters \fBC\fP and \fBS\fP. Concerning the return value of \fBsnprintf\fP(), SUSv2 and C99 contradict each other: when \fBsnprintf\fP() is called with \fIsize\fP=0 then SUSv2 stipulates an unspecified return value less than 1, while C99 allows \fIstr\fP 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 \fBsnprintf\fP() with C99. .PP glibc 2.1 añade los modificadores de longitud \fBhh\fP, \fBj\fP, \fBt\fP y \fBz\fP y los caracteres de conversión \fBa\fP y \fBA\fP. .PP glibc 2.2 añade el carácter de conversión \fBF\fP con la semántica de C99, y el carácter de opción \fBI\fP. .SH NOTAS Some programs imprudently rely on code such as the following .PP sprintf(buf, "%s some further text", buf); .PP .\" http://sourceware.org/bugzilla/show_bug.cgi?id=7075 to append text to \fIbuf\fP. However, the standards explicitly note that the results are undefined if source and destination buffers overlap when calling \fBsprintf\fP(), \fBsnprintf\fP(), \fBvsprintf\fP(), and \fBvsnprintf\fP(). Depending on the version of \fBgcc\fP(1) used, and the compiler options employed, calls such as the above will \fBnot\fP produce the expected results. .PP .\" .SH HISTORY .\" UNIX V7 defines the three routines .\" .BR printf (), .\" .BR fprintf (), .\" .BR sprintf (), .\" and has the flag \-, the width or precision *, the length modifier l, .\" and the conversions doxfegcsu, and also D,O,U,X as synonyms for ld,lo,lu,lx. .\" This is still true for 2.9.1BSD, but 2.10BSD has the flags .\" #, + and and no longer mentions D,O,U,X. .\" 2.11BSD has .\" .BR vprintf (), .\" .BR vfprintf (), .\" .BR vsprintf (), .\" and warns not to use D,O,U,X. .\" 4.3BSD Reno has the flag 0, the length modifiers h and L, .\" and the conversions n, p, E, G, X (with current meaning) .\" and deprecates D,O,U. .\" 4.4BSD introduces the functions .\" .BR snprintf () .\" and .\" .BR vsnprintf (), .\" and the length modifier q. .\" FreeBSD also has functions .\" .BR asprintf () .\" and .\" .BR vasprintf (), .\" that allocate a buffer large enough for .\" .BR sprintf (). .\" In glibc there are functions .\" .BR dprintf () .\" and .\" .BR vdprintf () .\" that print to a file descriptor instead of a stream. La implementación de glibc de las funciones \fBsnprintf\fP() y \fBvsnprintf\fP() 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. .SH ERRORES .\" .PP .\" Linux libc4.[45] does not have a .\" .BR snprintf (), .\" but provides a libbsd that contains an .\" .BR snprintf () .\" equivalent to .\" .BR sprintf (), .\" that is, one that ignores the .\" .I size .\" argument. .\" Thus, the use of .\" .BR snprintf () .\" with early libc4 leads to serious security problems. Ya que \fBsprintf\fP() y \fBvsprintf\fP() 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 \fBsnprintf\fP() y \fBvsnprintf\fP() en su lugar (o \fBasprintf\fP(3) y \fBvasprintf\fP(3)). .PP .\" .PP .\" Some floating-point conversions under early libc4 .\" caused memory leaks. Fragmentos de código como \fBprintf(\fP\fIfoo\fP\fB);\fP indican a menudo un fallo, puesto que \fIfoo\fP puede contener un carácter %. Si \fIfoo\fP proviene de la entrada del usuario, puede contener \fB%n\fP, provocando que la llamada \fBprintf\fP() escriba en memoria y creando un agujero de seguridad. .SH EJEMPLOS Para imprimir \fIPi\fP con cinco cifras decimales: .PP .in +4n .EX #include #include fprintf(stdout, "pi = %.5f\en", 4 * atan(1.0)); .EE .in .PP Para imprimir una fecha y una hora de la forma "Sunday, July 3, 10:02", donde \fIweekday\fP y \fImonth\fP son punteros a cadenas: .PP .in +4n .EX #include fprintf(stdout, "%s, %s %d, %.2d:%.2d\en", weekday, month, day, hour, min); .EE .in .PP 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: .PP .in +4n .EX #include fprintf(stdout, formato, diasemana, mes, día, hora, min); .EE .in .PP donde \fIformato\fP depende de la localización y puede permutar los argumentos. Con el valor .PP .in +4n .EX "%1$s, %3$d. %2$s, %4$d:%5$.2d\en" .EE .in .PP se podría obtener "Sonntag, 3. Juli, 10:02". .PP 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): .PP .EX #include #include #include 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 \(aq\e0\(aq */ 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; } .EE .PP If truncation occurs in glibc versions prior to 2.0.6, this is treated as an error instead of being handled gracefully. .SH "VÉASE TAMBIÉN" \fBprintf\fP(1), \fBasprintf\fP(3), \fBputs\fP(3), \fBscanf\fP(3), \fBsetlocale\fP(3), \fBstrfromd\fP(3), \fBwcrtomb\fP(3), \fBwprintf\fP(3), \fBlocale\fP(5) .SH COLOFÓN Esta página es parte de la versión 5.10 del proyecto Linux \fIman\-pages\fP. 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/. .PP .SH TRADUCCIÓN La traducción al español de esta página del manual fue creada por Sebastian Desimone , juanma , Juan Piernas y Miguel Pérez Ibars . .PP Esta traducción es documentación libre; lea la .UR https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License Version 3 .UE o posterior con respecto a las condiciones de copyright. No existe NINGUNA RESPONSABILIDAD. .PP Si encuentra algún error en la traducción de esta página del manual, envíe un correo electrónico a .MT debian-l10n-spanish@lists.debian.org .ME .