F. Biblioteca de funciones estándar ANSI/ISO C++
F. Biblioteca de funciones estándar ANSI/ISO C++
F. Biblioteca de funciones estándar ANSI/ISO C++
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
APÉNDICE F<br />
BIBLIOTECA DE FUNCIONES ESTÁNDAR<br />
<strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0<br />
CONTENIDO<br />
F.1.<br />
F.2.<br />
F.3.<br />
F.4.<br />
F.5.<br />
F.6.<br />
F.7.<br />
Plantilla referencia <strong>de</strong> entradas.<br />
Funciones <strong>de</strong> asignación <strong>de</strong> memoria.<br />
Funciones <strong>de</strong> búsqueda y or<strong>de</strong>nación.<br />
Funciones <strong>de</strong> ca<strong>de</strong>na.<br />
Funciones <strong>de</strong> clasificación <strong>de</strong> caracteres.<br />
Funciones <strong>de</strong> calendario (fecha y hora).<br />
Funciones <strong>de</strong> control <strong>de</strong> directorios.<br />
F.8. Funciones <strong>de</strong> control <strong>de</strong> procesos.<br />
F.9. Funciones <strong>de</strong> conversión <strong>de</strong> datos.<br />
F.10. Funciones <strong>de</strong> entrada/salida.<br />
F.11. Funciones <strong>de</strong> gestión <strong>de</strong> archivos.<br />
F.12. Funciones matemáticas.<br />
F.13. Funciones <strong>de</strong> manipulación <strong>de</strong> bloques <strong>de</strong> memoria (buffers).<br />
F.14. Funciones <strong>de</strong> presentación <strong>de</strong> texto.<br />
Esta parte es una revisión breve <strong>de</strong> la biblioteca <strong>de</strong> rutinas (<strong>funciones</strong>) y<br />
archivos inclu<strong>de</strong>, en tiempo <strong>de</strong> ejecución. La biblioteca <strong>de</strong> Borland <strong>C++</strong> es<br />
un conjunto <strong>de</strong> más <strong>de</strong> 450 <strong>funciones</strong> y macros preparadas para utilizar y<br />
diseñadas para su uso en programas <strong>C++</strong>. La biblioteca en tiempo <strong>de</strong> ejecución<br />
hace la programación más fácil, ya que incluye una amplia variedad <strong>de</strong><br />
tareas tales como E/S <strong>de</strong> bajo y alto nivel, manipulación <strong>de</strong> ca<strong>de</strong>nas y archivos,<br />
asignación <strong>de</strong> memoria, control <strong>de</strong> procesos, cálculos matemáticos, etc.<br />
Las rutinas <strong>de</strong> Borland <strong>C++</strong> están contenidas en los archivos <strong>de</strong> biblioteca<br />
Cx.LIB, CPx.LIB, MATHx.LIB y GRAPHICS.LIB. Borland <strong>C++</strong> implementa<br />
la versión estándar última <strong>de</strong> <strong>ANSI</strong> C, que entre otras cosas recomienda<br />
el uso <strong>de</strong> los prototipos <strong>de</strong> función en las rutinas <strong>de</strong> sus programas <strong>C++</strong>.<br />
Este apéndice <strong>de</strong>scribe alfabeticamente <strong>funciones</strong> <strong>de</strong> la biblioteca Borland<br />
<strong>C++</strong> y contiene todas las <strong>funciones</strong> incluidas en <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong>.<br />
F.1.<br />
PLANTILLA REFERENCIA DE ENTRADAS<br />
Las entradas <strong>de</strong> las diferentes <strong>funciones</strong> y macros han sido normalizadas<br />
para facilidad <strong>de</strong> manejo <strong>de</strong>l lector. Las rutinas han sido clasificadas por<br />
categorías (en general, se ha procurado respetar la clasificación dada por<br />
Borland y <strong>ANSI</strong>, pero con una adaptación más próxima al uso diario <strong>de</strong>l<br />
programador /.<br />
Al comienzo <strong>de</strong> cada categoría se hace una breve <strong>de</strong>scripción <strong>de</strong> su<br />
cometido principal y se presenta una tabla con las <strong>funciones</strong> que contiene<br />
cada categoría por or<strong>de</strong>n alfabético, así como una breve síntesis <strong>de</strong> su <strong>de</strong>scripción<br />
o propósito. A continuación, por or<strong>de</strong>n alfabético, se <strong>de</strong>scriben las<br />
rutinas <strong>de</strong> acuerdo al siguiente mo<strong>de</strong>lo para cada entrada.<br />
F.2.<br />
FUNCIONES DE ASIGNACIÓN DE MEMORIA<br />
Borland <strong>C++</strong> almacena información en la memoria principal <strong>de</strong> la computadora<br />
por dos métodos. El primero utiliza variables globales y locales<br />
(incluyendo arrays, ca<strong>de</strong>nas y estructura); en este caso, el almacenamiento<br />
o longitu<strong>de</strong>s fija. Para cambiar el tamaño <strong>de</strong> arrays y ca<strong>de</strong>nas <strong>de</strong> caracteres<br />
se <strong>de</strong>be editar el archivo fuente y recompilar su programa. Esta información<br />
se almacena en la pila (stack). El segundo método <strong>de</strong> almacenar información<br />
es asignar memoria a medida que el programa lo requiera y liberar esta<br />
memoria cuando ya no se necesita; esta acción permite utilizar la misma<br />
nombre función<br />
• strrev<br />
char *strrev(char *cad)<br />
sintaxis<br />
archivo <strong>de</strong> cabecera<br />
#inclu<strong>de</strong> <br />
Descripción<br />
Propósito y breve <strong>de</strong>scripción <strong>de</strong> cómo y dón<strong>de</strong> se utiliza la función.<br />
Ejemplo<br />
Una o más instrucciones o programas sencillos, don<strong>de</strong> se muestra la explicación<br />
real <strong>de</strong> la función.<br />
Funciones relacionadas: strcpy, strncpy.<br />
Funciones relacionadas con la función <strong>de</strong>scrita.
616 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
memoria para colas diferentes en un tiempo distinto. Este proceso <strong>de</strong> asignar<br />
memoria se <strong>de</strong>nomina asignación dinámica <strong>de</strong> memoria.<br />
Por omisión, cada vez que se ejecuta un programa, DOS establece un<br />
segmento <strong>de</strong> 64 Kb <strong>de</strong>nominado segmento <strong>de</strong> código, que contiene su código<br />
programa. DOS establece también un segmento <strong>de</strong> 64 Kb <strong>de</strong>nominado<br />
segmento <strong>de</strong> datos. Su programa pue<strong>de</strong> tener múltiples segmentos <strong>de</strong> datos<br />
y códigos.<br />
El segmento <strong>de</strong> datos se divi<strong>de</strong> en tres regiones: datos <strong>de</strong>l programa<br />
(variables estáticas y globales), pila —stack— (variables locales y argumentos)<br />
y montón o montículo —heap.<br />
Segmento <strong>de</strong> datos<br />
Montículo Pila Datos <strong>de</strong>l programa<br />
(heap)<br />
(stack)<br />
Después <strong>de</strong> asignar partes <strong>de</strong>l segmento <strong>de</strong> datos a variables estáticas y<br />
globales y a la pila, el compilador <strong>de</strong>dica el resto <strong>de</strong>l segmento <strong>de</strong> datos al<br />
montículo o heap.<br />
Borland <strong>C++</strong> contiene un gran número <strong>de</strong> <strong>funciones</strong> para asignación<br />
dinámica <strong>de</strong> memoria, que realizan una gran variedad <strong>de</strong> tareas: asignar y<br />
liberar memoria <strong>de</strong>l montículo y <strong>de</strong> la pila, obtener información <strong>de</strong> bloques<br />
<strong>de</strong> memoria, etc.<br />
datos <strong>de</strong> un programa. Si hay éxito se <strong>de</strong>vuelve 0; en caso contrario, –1, y la<br />
variable global errnoc toma el valor ENOMEN (insuficiente memoria).<br />
it(brk(nuevo_break) == -1)<br />
perror(“brk ha fallado”);<br />
Funciones relacionadas: free, farmalloc, malloc, sbrk.<br />
calloc<br />
int *calloc(size_t n, size_t s);<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
Asigna memoria principal (un bloque <strong>de</strong> tamaño n.s). El bloque se<br />
borra (limpia) a 0. Si se <strong>de</strong>sea asignar un bloque mayor que 64 Kb, se <strong>de</strong>be<br />
utilizar farcalloc. Devuelve un puntero al bloque recién asignado. Si no<br />
existe bastante espacio para el nuevo bloque o bien n o s es 0, calloc<br />
<strong>de</strong>vuelve nulo.<br />
long *buffer<br />
buffer=(long *) calloc(40, sizeof(long));<br />
Funciones relacionadas free, malloc.<br />
allocmen<br />
int allocmen(unsigned t, unsigned * seg);<br />
#inclu<strong>de</strong> <br />
La función allocmen() establece seg para apuntar a un segmento asignado<br />
<strong>de</strong> memoria <strong>de</strong> t párrafos (1 párrafo = 16 bytes) <strong>de</strong> largo. Si hay éxito<br />
se <strong>de</strong>vuelve –1, si hay error (falta memoria), allocmen() <strong>de</strong>vuelve el<br />
tamaño en párrafos <strong>de</strong>l mayor bloque disponible.<br />
if(allocmen(size, &segadd)!= -1)<br />
printf (“Error asignación memoria \n”);<br />
Funciones relacionadas: falloc frremem, malloc, setblock.<br />
brk<br />
#inclu<strong>de</strong> <br />
int brk( void* a)<br />
La función brk permite modificar el «valor break» <strong>de</strong> un programa. El<br />
valor break es la dirección <strong>de</strong> la primera posición más allá <strong>de</strong>l segmento <strong>de</strong><br />
coreleft<br />
#inclu<strong>de</strong> <br />
unsigned coreleft(void) // mo<strong>de</strong>los small, tiny, medium<br />
unsigned long coreleft(void); // en otros mo<strong>de</strong>los <strong>de</strong> memoria<br />
Determina la cantidad <strong>de</strong> memoria no utilizada. El valor <strong>de</strong>vuelto<br />
<strong>de</strong>pen<strong>de</strong> <strong>de</strong>l mo<strong>de</strong>lo <strong>de</strong> memoria.<br />
Mem_avail = coreleft();<br />
Funciones relacionadas: calloc, farcoreleft, malloc.<br />
farcalloc<br />
#inclu<strong>de</strong> <br />
void far *farcalloc(unsigned long n, unsigned long s);<br />
Esta función asigna n piezas <strong>de</strong> tamaño s y las pone a 0. Un puntero al<br />
principio <strong>de</strong> la memoria asignada se <strong>de</strong>vuelve si farcalloc() tiene éxito;<br />
en caso contrario se <strong>de</strong>vuelve NULL.
BIBLIOTECA DE FUNCIONES ESTÁNDAR <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0 617<br />
if(array_gran<strong>de</strong>=farcalloc(20000L, sizeof (int)) “” NULL)<br />
printf (“Fallo en asignación <strong>de</strong> memoria\n”);<br />
Funciones relacionadas: farheapfillfree, farheapwalk, heapfillfree,<br />
heapcheckfree, heapwalk.<br />
Funciones relacionadas: calloc, farfree, farmalloc, malloc.<br />
farheapcheckno<strong>de</strong><br />
#inclu<strong>de</strong> <br />
farcoreleft<br />
unsigned long farcoreleft(void);<br />
#inclu<strong>de</strong> <br />
int farheapcheckno<strong>de</strong>(void *bloque);<br />
Verifica la consistencia <strong>de</strong> un solo bloque en el montículo (heap) far.<br />
Determina el número total <strong>de</strong> bytes disponibles en el sistema.<br />
estadoheap = farheapcheckno<strong>de</strong>(arraygran<strong>de</strong>);<br />
memoria_total_disponible = farcoreleft();<br />
Funciones relacionadas: coreleft, farcalloc, farmalloc.<br />
farheapfillfree<br />
int farheapfillfree(unsigned int f);<br />
#inclu<strong>de</strong> <br />
farfree<br />
void farfree(void far *b);<br />
Libera la memoria apuntada por b.<br />
farfree(arraygran<strong>de</strong>);<br />
#inclu<strong>de</strong> <br />
Rellena todos los bloques libres <strong>de</strong>l montículo far con un valor constante.<br />
estadoheap = farheapfillfree(´X´);<br />
Funciones relacionadas: farheapcheckfree, farheapcheckno<strong>de</strong>,<br />
farheapwalk, heapfillfree, heapwalk.<br />
Funciones relacionadas: farcalloc, farmalloc, farrealloc, free.<br />
farheapwalk<br />
#inclu<strong>de</strong> <br />
farheapcheck<br />
#inclu<strong>de</strong> <br />
int farheapcheck(void);<br />
Verifica la consistencia <strong>de</strong>l montículo (heap) far.<br />
estadoheap = farheapcheck();<br />
Funciones relacionadas: farheapcheckfree, farheapcheckno<strong>de</strong>,<br />
farheapwalk, heapfillfree, heapwalk, heapcheck.<br />
farheapcheckfree<br />
#inclu<strong>de</strong> <br />
int farheapcheckfree(unsigned int f);<br />
Verifica la consistencia <strong>de</strong> los bloques libres en el montículo (heap) far.<br />
estadoheap = farheapcheckfree(´F´);<br />
int farheapwalk(struct farheapinfo *m);<br />
Obtiene información sobre las entradas en el montículo (heap) far.<br />
struct farheapinfo heap_entry;<br />
estadopila = farheapwalk(&heap_entry);<br />
farmalloc<br />
void far *farmalloc(unsigned long n);<br />
#inclu<strong>de</strong> <br />
Asigna n bytes <strong>de</strong> memoria far. La cantidad completa <strong>de</strong> memoria<br />
encima <strong>de</strong> la pila está disponible para asignación por farmalloc. El tamaño<br />
<strong>de</strong>l bloque pue<strong>de</strong> exce<strong>de</strong>r <strong>de</strong> 64 Kb.<br />
if(bloquegran<strong>de</strong> = farmalloc(80000L) == NULL<br />
printf(“Asignación fallada\n”);<br />
Funciones relacionadas: calloc, farfree, farcalloc, malloc.
618 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
farrealloc<br />
#inclu<strong>de</strong> <br />
heapcheckfree<br />
#inclu<strong>de</strong> <br />
void far *farrealloc(void far *b, unsigned long n)<br />
Se utiliza para reasignar (ajustar el tamaño <strong>de</strong> un bloque <strong>de</strong> memoria b,<br />
al cual se ha asignado una longitud <strong>de</strong> n bytes).<br />
if(bloquegran<strong>de</strong> = farrealloc(bloquegran<strong>de</strong>, 120000L)) = NULL<br />
printf(“Fallo reasignación memoria\n”);<br />
int heapcheckfree(unsigned int f);<br />
Verifica la consistencia <strong>de</strong> los bloques libres en el montículo (heap).<br />
estadoheap = heapcheckfree(´N´);<br />
Funciones relacionadas: farheapcheckfree, heapfillfree, heapwalk.<br />
Funciones relacionadas: calloc, farcalloc, farfree, malloc.<br />
heapcheckno<strong>de</strong><br />
#inclu<strong>de</strong> <br />
free<br />
vid free(void *dir_memoria);<br />
#inclu<strong>de</strong><br />
#inclu<strong>de</strong> <br />
int heapcheckno<strong>de</strong>(void *n);<br />
Verifica la consistencia <strong>de</strong> un solo nodo (bloque <strong>de</strong> memoria). Verifica<br />
el bloque <strong>de</strong> memoria i<strong>de</strong>ntificado por el puntero n.<br />
La función free() libera un bloque <strong>de</strong> memoria. El argumento<br />
dir_memoria apunta a un bloque <strong>de</strong> memoria previamente asignado a<br />
través <strong>de</strong> una llamada a calloc, malloc o realloc. Después <strong>de</strong> la llamada<br />
el bloque libre está disponible para asignación.<br />
char *cad;<br />
// asignar memoria para ca<strong>de</strong>na<br />
cad = (char *) malloc(50);<br />
...<br />
free(cad); // liberar memoria<br />
Funciones relacionadas: calloc, malloc, realloc<br />
estadopila = heapcheckno<strong>de</strong>(array);<br />
Funciones relacionadas: farheapcheckno<strong>de</strong>, heapcheck, heapcheckfree,<br />
heapfillfree, heapwalk.<br />
heapfillfree<br />
int heapfillfree(unsigned int f);<br />
#inclu<strong>de</strong> <br />
Rellena cada byte <strong>de</strong> todos los bloques <strong>de</strong> memoria no utilizados en el<br />
montículo con un valor <strong>de</strong> carácter especificado. En Visual <strong>C++</strong> la función<br />
equivalente es –heapset.<br />
heapcheck<br />
int heapcheck(void);<br />
#inclu<strong>de</strong> <br />
estadopila = heapfillfree(´Z´);<br />
Funciones relacionadas: farheapfillfree, heapcheck, heapcheckfree,<br />
heapwalk.<br />
Verifica la consistencia <strong>de</strong>l montículo (heap). En Visual <strong>C++</strong> 6.0 la función<br />
equivalente es _heapcheck();<br />
estadoheap = heapcheck();<br />
heapwalk<br />
int heapwalk(struct heapinfo *i);<br />
#inclu<strong>de</strong> <br />
Funciones relacionadas: heapcheckfree, heapcheckno<strong>de</strong>, heapfillfree,<br />
heapwalk, farheapcheck.<br />
Se utiliza para obtener información sobre las entradas en el montículo<br />
(heap). La función equivalente en Visual <strong>C++</strong> es _heapwalk.
BIBLIOTECA DE FUNCIONES ESTÁNDAR <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0 619<br />
struct heapinfo i;<br />
estadoheap = heapwalk(&i);<br />
Funciones relacionadas: farheapwalk, heapcheck.<br />
malloc<br />
void *malloc (size_t n);<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
Asigna memoria a bloques en el montículo. Devuelve un puntero, que<br />
es la dirección inicial <strong>de</strong> la memoria asignada.<br />
ca<strong>de</strong>na = malloc(MAX_CHR)<br />
Funciones relacionadas: calloc, free, realloc.<br />
setblock<br />
int setblock(unsigned seg, unsigned n);<br />
#inclu<strong>de</strong> <br />
Ajusta el tamaño <strong>de</strong> un bloque <strong>de</strong> memoria asignado anteriormente por<br />
allocmen. Esta función llama a la función 4Ah <strong>de</strong> DOS para ampliar el<br />
tamaño <strong>de</strong> un bloque <strong>de</strong> memoria previamente asignado por allocmen. En<br />
las versiones Visual <strong>C++</strong> la función equivalente es _dos_setblock.<br />
F.3.<br />
FUNCIONES DE BÚSQUEDA Y ORDENACIÓN<br />
La mayoría <strong>de</strong> los programas requieren casi siempre alguna operación <strong>de</strong><br />
clasificación y búsqueda <strong>de</strong> elementos en arrays. Borland <strong>C++</strong> incluye diferentes<br />
<strong>funciones</strong> que realizan estas tareas.<br />
bsearch()<br />
#inclu<strong>de</strong> <br />
realloc<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
void bsearch(const void*k, const void *b, size_t n, size_t a,<br />
int(*comparar)(const void*, const void*));<br />
void *realloc(void *b, size_t n);<br />
Ajusta el tamaño <strong>de</strong> un bloque <strong>de</strong> memoria b asignado por malloc o<br />
calloc a un tamaño <strong>de</strong> n bytes. Devuelve un puntero void al bloque <strong>de</strong><br />
memoria reasignado.<br />
Nuevo_buffer = realloc(viejo_buffer, long+100);<br />
Funciones relacionadas: calloc, free, malloc.<br />
La función bsearch realiza una búsqueda binaria en un array or<strong>de</strong>nado<br />
b, <strong>de</strong> n elementos, cada uno <strong>de</strong> a bytes <strong>de</strong> tamaño. El argumento k apunta<br />
al valor que se está buscando. bearch <strong>de</strong>vuelve un puntero (la dirección)<br />
a la primera aparición <strong>de</strong>l valor k en el array. Si no se encuentra el valor,<br />
bsearch <strong>de</strong>vuelve o.<br />
El argumento comparar proporciona la dirección <strong>de</strong> una rutina que<br />
aceptará dos argumentos elem1 y elem2, cada uno un puntero a un elemento<br />
<strong>de</strong>l array. La función comparar compara cada uno <strong>de</strong> los elementos apuntados<br />
y <strong>de</strong>vuelve un valor <strong>de</strong> acuerdo con la tabla siguiente:<br />
sbrk<br />
void *sbrk(int n);<br />
#inclu<strong>de</strong> <br />
Se utiliza sbrk para indicar el valor break <strong>de</strong> un proceso. El valor<br />
break es la dirección <strong>de</strong>l primer byte disponible en el segmento <strong>de</strong> datos por<br />
omisión, más allá <strong>de</strong>l segmento <strong>de</strong> datos que está siendo utilizado por los<br />
datos en el proceso.<br />
sbr(500);<br />
Funciones relacionadas: brk, coreleft<br />
Valor <strong>de</strong>vuelto<br />
Negativo<br />
Cero<br />
Positivo<br />
Condición<br />
Primer elemento menor que el segundo (elem1) (elem2).<br />
Los dos elementos son idénticos.<br />
Primer elemento mayor que el segundo.<br />
La búsqueda binaria requiere que el array esté or<strong>de</strong>nado, por lo cual,<br />
caso <strong>de</strong> que no esté or<strong>de</strong>nado el array, se pue<strong>de</strong> utilizar la función qsort<br />
para or<strong>de</strong>nar el array antes <strong>de</strong> llamar a bsearch.<br />
Funciones relacionadas: lfind, lsearch, qsort.
620 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
lfind<br />
#inclu<strong>de</strong> <br />
void * lfind(const void k, const void *b, size_t *num, size_t<br />
anchura, int(*comparar)(const void*, const void*));<br />
La función lfind() realiza una búsqueda lineal <strong>de</strong> valor <strong>de</strong> k (clave) en<br />
un array <strong>de</strong> un número específico <strong>de</strong> elementos, cada uno <strong>de</strong> un número fijo<br />
<strong>de</strong> bytes <strong>de</strong> longitud. Al contrario que bsearch(), el array no necesita<br />
estar or<strong>de</strong>nado. lfind() <strong>de</strong>vuelve un puntero al primer elemento <strong>de</strong>l array<br />
que coinci<strong>de</strong> con la clave; si la clave no existe en el array, se <strong>de</strong>vuelve un 0.<br />
int comp(const void*, const void *); resultado = (char **)<br />
lfind(palabrabuscada, envp, &cuenta, sizeof(char*), comp);<br />
Funciones relacionadas: bsearch, lsearch, qsort.<br />
lsearch<br />
#inclu<strong>de</strong> <br />
void * lsearch(const void *k, const void *a, size_t *n, size_t W,<br />
int(*comparar) (const void*, const void *));<br />
La función lsearch realiza una búsqueda lineal <strong>de</strong> la clave k. El<br />
array a contiene n elementos <strong>de</strong> anchura W. La función comparar se utiliza<br />
para comparar la clave con el elemento actual <strong>de</strong>l array. Al contrario<br />
que bsearch(), en la función lsearch() el array no tiene que estar<br />
or<strong>de</strong>nado. lsearch() <strong>de</strong>vuelve un puntero al primer elemento <strong>de</strong>l array<br />
que se correspon<strong>de</strong> con la clave. Si no existe la clave en el array, se<br />
<strong>de</strong>vuelve 0 y un registro se aña<strong>de</strong> al array con un valor <strong>de</strong> k.<br />
La diferencia entre lsearch() y lfind() es que lsearch() añadirá<br />
un registro al final <strong>de</strong>l array con un valor <strong>de</strong> la clave si ese registro no se ha<br />
encontrado en el array.<br />
Funciones relacionadas: bsearch, lfind, qsort.<br />
qsort<br />
#inclu<strong>de</strong> <br />
void qsort(void a, size_t n, size_t w, int(*comparar) (const void*,<br />
const void*));<br />
La función qsort or<strong>de</strong>na un array con un número dado <strong>de</strong> elementos<br />
utilizando el método <strong>de</strong> or<strong>de</strong>nación rápida quicksort (creado por C.A.R.<br />
Hoare). El número <strong>de</strong> elementos <strong>de</strong> array es n y el tamaño (en bytes) <strong>de</strong> cada<br />
elemento es w. La función comparar se utiliza para comparar un elemento<br />
<strong>de</strong>l array con la clave; <strong>de</strong>vuelve los siguientes valores:<br />
Valor <strong>de</strong>vuelto<br />
Negativo<br />
Cero<br />
Positivo<br />
Condición<br />
Primer elemento (elem1) menor que el segundo (elem2).<br />
Los dos elementos son idénticos.<br />
Primer elemento mayor que el segundo.<br />
Or<strong>de</strong>nar la lista <strong>de</strong> enteros y visualizar el resultado.<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
int comparar(const void*, const void *);<br />
int numeros[10] = {4,5,7,3,12,8,6,1,0,2};<br />
main(void)<br />
{<br />
int i;<br />
}<br />
printf(“lista original:”);<br />
for(i =0; i < 10; i++)<br />
printf(“%d”, numeros[i]);<br />
qsort(numeros,10,sizeof(int), comparar);<br />
printf(“lista or<strong>de</strong>nada:”);<br />
for(i = 0; i < 10; i++)<br />
printf(“%10, numeros[i]);<br />
return 0;<br />
// comparar enteros<br />
comparar(const void *i, const void *j)<br />
{<br />
return ((int *)i) – ((int *) j)<br />
}<br />
Funciones relacionadas: bsearch, lfind, lsearch.<br />
F.4.<br />
FUNCIONES DE CADENA<br />
C no tiene el tipo <strong>de</strong> datos ca<strong>de</strong>na (string). En su lugar, las ca<strong>de</strong>nas se tratan<br />
como arrays <strong>de</strong> caracteres, cada uno <strong>de</strong> los cuales ocupa un byte. Por notación<br />
el final <strong>de</strong> una ca<strong>de</strong>na en C se representa por un byte que contiene un carácter<br />
nulo (´\0´). Las ca<strong>de</strong>nas pue<strong>de</strong>n ser <strong>de</strong>claradas como arrays <strong>de</strong> caracteres.<br />
char cad[20], cad 5[] = “Hola Mortimer”;
BIBLIOTECA DE FUNCIONES ESTÁNDAR <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0 621<br />
Acceso a las ca<strong>de</strong>nas<br />
strchr<br />
#inclu<strong>de</strong> <br />
A las ca<strong>de</strong>nas se acce<strong>de</strong> directamente a través <strong>de</strong> su índice, como en el<br />
ejemplo anterior, o bien a través <strong>de</strong> un puntero.<br />
char cad5[] = “Hola Mortimer”;<br />
char *p_cad5;<br />
p_cad5 = cad5;<br />
Se pue<strong>de</strong> también <strong>de</strong>clarar e inicializar una ca<strong>de</strong>na a la vez:<br />
char *p_cad5 = “Hola Mortimer”;<br />
El archivo <strong>de</strong> cabecera contiene numerosas <strong>funciones</strong> que<br />
manipulan ca<strong>de</strong>nas.<br />
stpcpy<br />
#inclu<strong>de</strong> <br />
char *stpcpy(char *cad1, const char *cad2);<br />
La función stpcpy() copia una ca<strong>de</strong>na en otra. Devuelve un puntero al<br />
final <strong>de</strong> la ca<strong>de</strong>na copiada. Se <strong>de</strong>vuelve el valor <strong>de</strong> cad1+strlen(cad2)<br />
stpcpy(or<strong>de</strong>n_dos, “DIR”);<br />
stpcpy(caad1, cad2);<br />
Funciones relacionadas: strcat, strcpy, strncat, strncpy, strdup.<br />
strcat<br />
char *strcat(char *cad1, const char cad2);<br />
#inclu<strong>de</strong> <br />
strcat() concatena (aña<strong>de</strong>) cad1 al final <strong>de</strong> cad2, terminando la ca<strong>de</strong>na<br />
resultante con un carácter nulo (\0).<br />
char nombre[80] = “Bob”;<br />
char blanco[2] = “”;<br />
char ultimo[80] = “Marley”;<br />
...<br />
strcat(nombre,blanco); // blanco se concatena a nombre<br />
strcat(nombre,ultimo); // ultimo se concatena a nombre<br />
// la ca<strong>de</strong>na nombre será “Bob Marley”<br />
Funciones relacionadas: strcpy, strdup, strncat, strncpy.<br />
char *strchr(const char *cad, int c);<br />
strchr() encuentra la primera aparición <strong>de</strong> c en cad y <strong>de</strong>vuelve un<br />
puntero a la primera aparición <strong>de</strong> c en cad. Si c no se encuentra, <strong>de</strong>vuelve<br />
un cero (NULL).<br />
printf(“%s”, strchr(“Salario mensual = $85725”, ´$´));<br />
visualizará $85725<br />
char *s[81] = “Esta es una ca<strong>de</strong>na <strong>de</strong> prueba”;<br />
char *ptr;<br />
ptr = strchr(s, ´a´);<br />
el valor almacenado en ptr es un puntero a la primera aparición <strong>de</strong> ´a´.<br />
strcmp<br />
int strcmp(const char *a, const char *b);<br />
Compara una ca<strong>de</strong>na con otra. Los resultados serían:<br />
> 0 si a > b<br />
= 0 si a == b<br />
< 0 si a < b<br />
i = strcmp(“MNP”, “mnp”); // resultado < 0<br />
i = strcmp(“abc”, “abc”); // resultado = 0<br />
i = strcmp(“xy”, “abc”); // resultado > 0<br />
char s1[80] “ “Mayo”;<br />
char s2[80] = “Octubre”;<br />
int j;<br />
j = strcmp(s1, s2);<br />
#inclu<strong>de</strong> <br />
Funciones relacionadas: strcmpi, stricmp, strnicmp, strncmp.<br />
strcmpi<br />
#inclu<strong>de</strong> <br />
int strcmpi(const char *cad1, const char * call2);<br />
Compara una ca<strong>de</strong>na con otra sin diferenciar entre mayúsculas y minúsculas<br />
y <strong>de</strong>vuelve un entero:
622 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
< 0 si cad1 < cad2<br />
= 0 si cad1 = cad2<br />
> 0 si cad1 > cad2<br />
v = strcmpi(c1, c2);<br />
Funciones relacionadas: strcmp, stricmp, strncmp, strnicmp.<br />
Localiza la posición <strong>de</strong> la primera aparición en una ca<strong>de</strong>na <strong>de</strong> cualquier<br />
carácter <strong>de</strong> otra ca<strong>de</strong>na. Si tiene éxito, la función strcspn <strong>de</strong>vuelve el índice<br />
<strong>de</strong>l primer carácter <strong>de</strong> cad1, que pertenece al conjunto <strong>de</strong> caracteres <strong>de</strong><br />
cad2.<br />
primero = strcspn(“circunloquio”, “q”);<br />
// primero = 8<br />
Funciones relacionadas: strpbrk, strspn.<br />
strcoll<br />
int strcoll(const char *cad1, const char cad2);<br />
Compara cad1 con cad2. Devuelve un valor.<br />
< 0 si cad1 < cad2<br />
= 0 si cad1 = cad2<br />
> 0 si cad1 > cad2<br />
if(strcoll(nombre1, nombre2)! = 0)<br />
exit(EXIT_FAILURE);<br />
Funciones relacionadas:<br />
strxfrm.<br />
strcpy()<br />
#inclu<strong>de</strong> <br />
setlocate, strcmp, strcmpi, strncmp,<br />
char *strcpy(char *cad1, const char *cad2);<br />
#inclu<strong>de</strong> <br />
strcpy() copia cad2 en cad1. Si la longitud <strong>de</strong> la ca<strong>de</strong>na resultante<br />
exce<strong>de</strong> el tamaño asignado a cad1, pue<strong>de</strong> producir fallos en el programa.<br />
char *a = “Pepe Luis”;<br />
char b[12];<br />
strcpy(b, a);<br />
cout
BIBLIOTECA DE FUNCIONES ESTÁNDAR <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0 623<br />
strerror<br />
char *strerror(const char *cad);<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> stdio.h<br />
Esta función sirve para generar un mensaje <strong>de</strong> error <strong>de</strong>finido por el<br />
usuario.<br />
printf(“%S”, _strerror(“error apertura archivo”));<br />
Funciones relacionadas: perror, strerror.<br />
strlwr<br />
char *strlwr(char *cad);<br />
#inclu<strong>de</strong> <br />
Convierte una ca<strong>de</strong>na en letras minúsculas. La función <strong>de</strong>vuelve un<br />
puntero a la ca<strong>de</strong>na convertida.<br />
char *or<strong>de</strong>n =”SALIR”;<br />
strlwr(or<strong>de</strong>n); // ahora or<strong>de</strong>n = “salir”;<br />
Funciones relacionadas: strupr, toloweer.<br />
stricmp<br />
#inclu<strong>de</strong> <br />
strncat<br />
#inclu<strong>de</strong> <br />
it stricmp(const char *cad1, const char *cad2);<br />
Esta función se utiliza para comparar una ca<strong>de</strong>na a otra sin tener en<br />
cuenta el tamaño <strong>de</strong> las letras. Convierte todos los caracteres alfabéticos <strong>de</strong><br />
cad1 y cad2 en minúsculas; a continuación, se comparan las dos ca<strong>de</strong>nas y<br />
<strong>de</strong>vuelve un valor entero que indica el or<strong>de</strong>n lexicográfico <strong>de</strong> cad1 con respecto<br />
a cad2.<br />
Si cad1 = cad2<br />
Si cad1 < cad2<br />
Si cad1 > cad2<br />
Resultado = stricmp(cad1, cad2),<br />
el valor <strong>de</strong> la función es cero.<br />
el valor <strong>de</strong> la función es menor que cero.<br />
el valor <strong>de</strong> la función es mayor que cero.<br />
Funciones relacionadas: strcmp, strcmpi, strncmp, strnicmp.<br />
char *strncat(char *cad1, const char *cad2, size_t n);<br />
La función strncat() aña<strong>de</strong> los primeros n caracteres <strong>de</strong> cad2 a cad1,<br />
y termina la ca<strong>de</strong>na resultante un carácter nulo. Si cad2 es mayor que n<br />
caracteres <strong>de</strong> longitud, strncat() truncará la ca<strong>de</strong>na a la longitud <strong>de</strong> n. En<br />
otro caso, concatenará la ca<strong>de</strong>na completa.<br />
char *a = “Sierra Madre”;<br />
char *b = “<strong>de</strong> la ciudad <strong>de</strong> Monterrey”;<br />
cout
624 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
cout
BIBLIOTECA DE FUNCIONES ESTÁNDAR <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0 625<br />
strspn<br />
sze_t strspn(const char *cad1, constchar *cad2);<br />
#inclu<strong>de</strong> <br />
Localiza la posición <strong>de</strong>l primer carácter <strong>de</strong> una ca<strong>de</strong>na (cad1) que no<br />
pertenece al conjunto <strong>de</strong> caracteres <strong>de</strong> otra (cad2).<br />
loc = strspn (cad1, blanco);<br />
Convierte cualquier letra minúscula <strong>de</strong> la ca<strong>de</strong>na en mayúscula y<br />
<strong>de</strong>vuelve un puntero a la ca<strong>de</strong>na convertida (sólo alfabeto inglés).<br />
La función strupr y su homónima strlwr no forman parte <strong>de</strong> la biblioteca<br />
<strong>ANSI</strong> C. En estos casos, utilice las <strong>funciones</strong> toupper y tolower.<br />
strupr(“sierra madre”);<br />
Funciones relacionadas: strlwr, toupper.<br />
// “SIERRA MADRE”<br />
Funciones relacionadas: strcmp, strcspn.<br />
strxfrm<br />
#inclu<strong>de</strong> <br />
strstr<br />
#inclu<strong>de</strong> <br />
size_t strxfrm(char *cad1, char *cad2, size_t n);<br />
char *strstr(const char *cad1, const char *cad2);<br />
Localiza la primera aparición <strong>de</strong> una ca<strong>de</strong>na en otra. Si tiene éxito, la<br />
función strstr <strong>de</strong>vuelve un puntero a la primera aparición <strong>de</strong> cad2 como<br />
una subca<strong>de</strong>na <strong>de</strong> cad1. Si la búsqueda falla, se <strong>de</strong>vuelve NULL.<br />
char *s = “Mi autor favorito es Octavio Paz”<br />
char *a = “Octavio Paz”;<br />
cout
626 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
Asimismo, existen otras <strong>funciones</strong> en el archivo ctype.h que sirven<br />
para convertir caracteres en mayúsculas en minúsculas, y viceversa; y valores<br />
enteros en códigos ASCII.<br />
iscntrl, isdigit<br />
isgraph, islower<br />
isprint, ispunct, isspace<br />
isupper,isxdigit<br />
#inclu<strong>de</strong> <br />
isalnum<br />
int isalnum(int c);<br />
#inclu<strong>de</strong> <br />
La función isalnum() <strong>de</strong>vuelve un cero si c es un carácter no alfanumérico<br />
y un valor distinto <strong>de</strong> cero si el carácter es alfanumérico.<br />
carac = getch();<br />
if(isalnum(carac))<br />
printf(“%c letra|digito \n”, carac);<br />
else<br />
printf(“%c no letra|digito \n”, carac);<br />
Funciones relacionadas: isascii.<br />
int iscntrl(int c);<br />
int isdigit(int c);<br />
int isgraph(int c);<br />
int islower(int c);<br />
int isprint(int c);<br />
int ispunct(int c);<br />
int isspace(int c);<br />
int isupper(int c);<br />
int isxdigit(int c);<br />
Estas macros sirven para <strong>de</strong>terminar propieda<strong>de</strong>s específicas <strong>de</strong> un<br />
carácter ASCII.<br />
isalpha<br />
#inclu<strong>de</strong> <br />
Macro Verifica Rango válido <strong>de</strong> valores<br />
int isalpha(int c);<br />
La función isalpha() verifica si un carácter es alfabético. Devuelve un<br />
valor distinto <strong>de</strong> cero si c es un carácter alfabético, o 0 si c no es alfabético.<br />
int c = getah()<br />
if(isalpha©) printf(“%c es letra\n”, c);<br />
Funciones relacionadas: iascii.<br />
isascii<br />
#inclu<strong>de</strong> ctype.h><br />
iscntrl Carácter <strong>de</strong> control. 0..1Fh, 7Fh<br />
isdigit Dígito <strong>de</strong>cimal. ´0´..´9´<br />
isgraph Carácter imprimible (sin espacio). 21h a 7Eh<br />
islower Carácter minúscula. ´a´..´z´´<br />
isprint Carácter imprimible 20h..7Eh<br />
ispunct Carácter puntuación 21h..2Fh, 3Ah..40h,<br />
5Bh..60h, 7Bh..7Eh<br />
isspace Carácter blanco. 9h..Dh 0 20h (blanco)<br />
isupper Carácter mayúscula. ´A´..´Z´<br />
isxdigit Dígito hexa<strong>de</strong>cimal. ´0´..´9´<br />
´A´..´F´<br />
´a´.. f´<br />
int isascii(int c);<br />
Comprueba si un carácter c es un carácter ASCII; c está en el rango 0-127.<br />
Los caracteres 128 a 255 <strong>de</strong> ASCII son tratados por iascii() como no ASCII.<br />
carac = getch();<br />
if(isascii(carac))<br />
printf(“%c es ASCII \n”, carac);<br />
else<br />
printf(“%c no es ASCII \n”, carac);<br />
Funciones relacionadas: toascii, isalnum, isdigit,<br />
Cada macro (función) <strong>de</strong>vuelve un valor distinto <strong>de</strong> cero si c satisface<br />
el criterio <strong>de</strong> esa macro; en caso contrario, <strong>de</strong>vuelve un cero.<br />
if(isprint(c)) printf(“\n %c imprimible\n”, c);<br />
if(iscntrl(c)) printf(“%c es un carácter <strong>de</strong> control\”, c);<br />
if(isdigit(c)) printf(“%c es un dígito\n”, c);<br />
if(islower(c)) printf(“%c es letra minúscula\n”, c)<br />
Funciones relacionadas: iascii.
BIBLIOTECA DE FUNCIONES ESTÁNDAR <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0 627<br />
toascii<br />
#inclu<strong>de</strong> <br />
F.6.<br />
FUNCIONES DE CALENDARIO (FECHA Y HORA)<br />
int toascii(int c);<br />
Esta función convierte un valor entero en un carácter ASCII válido.<br />
C = toascii(entero);<br />
Las <strong>funciones</strong> <strong>de</strong> calendario (fecha y hora) permiten obtener la hora actual<br />
y, a continuación, convertirla y almacenarla <strong>de</strong> acuerdo a sus necesida<strong>de</strong>s<br />
particulares. La hora actual se toma siempre <strong>de</strong> la hora <strong>de</strong>l sistema. Las <strong>funciones</strong><br />
<strong>de</strong> calendario están incluidas en el archivo <strong>de</strong> cabecera time.h.<br />
Funciones relacionadas: iascii.<br />
asctime<br />
#inclu<strong>de</strong> <br />
_tolower<br />
tolower<br />
int _tolower(int c);<br />
int tolower(int c);<br />
#inclu<strong>de</strong> <br />
Convierte un carácter mayúscula en minúscula. Utilice _tolower sólo<br />
cuando esté seguro <strong>de</strong> que el carácter que quiere convertir es una letra<br />
mayúscula.<br />
La función _tolower() sólo está disponible en sistemas UNIX. Por<br />
consiguiente, para asegurar la compatibilidad utilice sólo la función tolower().<br />
c = tolower(´S´);<br />
// c se convierte en ´S´<br />
Funciones relacionadas: iascii, _toupper, toupper.<br />
char *asctime(const struct tm *hora);<br />
Convierte la fecha y la hora almacenada en una estructura <strong>de</strong> tipo tm en<br />
una ca<strong>de</strong>na <strong>de</strong> caracteres. La estructura tm se <strong>de</strong>fine en time.h así:<br />
struct tm<br />
{<br />
int tm_sec;<br />
int tm_min;<br />
int tm_hour;<br />
int tm_mday;<br />
int tm_mon;<br />
int tm_year;<br />
int tm_wday;<br />
int tm_yday;<br />
int tm_isdst;<br />
};<br />
// [0,59], segundos<br />
// [0,59], minutos<br />
// [0,23], horas<br />
// [1,31], dias <strong>de</strong>l mes<br />
// [0,11], mes <strong>de</strong>l año<br />
// [<strong>de</strong>s<strong>de</strong> 1900], año<br />
// [0,6], dias <strong>de</strong>s<strong>de</strong> domingo<br />
// [0,265], numero dia año<br />
// indicador hora <strong>de</strong> verano<br />
printf(“Fecha/hora es %s\n”, asctime(&reloj));<br />
_toupper<br />
touper<br />
#inclu<strong>de</strong> <br />
Funciones relacionadas:<br />
time.<br />
ctime, gmtime, clocaltime, strftime,<br />
int _toupper(int c);<br />
int _toupper(int c);<br />
int c; // carácter a convertir<br />
Estas <strong>funciones</strong> convierten un carácter minúscula en mayúscula. Utilice<br />
_toupper sólo cuando esté seguro <strong>de</strong> que el carácter que quiere convertir<br />
es una letra minúscula (rango a-z).<br />
La macro _toupper no está disponible en <strong>ANSI</strong> C. Para asegurar la<br />
compatibilidad, utilice siempre toupper().<br />
c = toupper(´S´);<br />
// c se convierte en ´S´<br />
Funciones relacionadas: iascii, _tolower, tolower.<br />
clock<br />
cock_t clock(void);<br />
#inclu<strong>de</strong> <br />
Calcula el tiempo empleado por el proceso llamador, es <strong>de</strong>cir, el tiempo<br />
utilizado <strong>de</strong> procesador. Devuelve un valor en ticks que ha <strong>de</strong> dividirse<br />
por la constante CLK_TCK para obtener el tiempo transcurrido en segundos.<br />
clock_t inicio, fin;<br />
printf(“Inicio:%f\n, clock()/CLK_TCK;<br />
Funciones relacionadas: gettime, time.
628 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
ctime<br />
#inclu<strong>de</strong> <br />
ftime<br />
#inclu<strong>de</strong> <br />
char *ctime(const time_t *hora);<br />
void ftime(struct timeb *ptrhora);<br />
Convierte la fecha y hora almacenada como valor <strong>de</strong> tipo time_t en una<br />
ca<strong>de</strong>na <strong>de</strong> caracteres (mes día hora año\0).<br />
Obtiene la hora actual y la almacena en la estructura timeb apuntada<br />
por ptrhora.<br />
time_t hora;<br />
hora = time(NULL);<br />
printf(“Hora actual=%s\n”, ctime(&hora));<br />
Funciones relacionadas: asctime, ftime, strtime, time.<br />
struct timeb {<br />
long time;<br />
short millitm;<br />
short timezone;<br />
short dstflag;<br />
};<br />
// segundos <strong>de</strong>s<strong>de</strong> 00:00:00 hora GMT<br />
// milisegundos<br />
// diferencia en minutos<br />
// hora Greenwich y hora local<br />
// hora <strong>de</strong> verano, ahorro <strong>de</strong> luz<br />
difftime<br />
#inclu<strong>de</strong> <br />
double difftime(time_t hora2, time_t hora1);<br />
Obtiene la diferencia entre dos tiempos en segundos.<br />
ftime(&hora);<br />
Funciones relacionadas: time tzset.<br />
getdate<br />
#inclu<strong>de</strong> <br />
time_t inicio, fin<br />
clrscrl();<br />
inicio = time(NULL);<br />
<strong>de</strong>lay (5000);<br />
fin = time(NULL);<br />
printf(“Diferencia en segundos: %f\n”,<br />
difftime(inicio, fin));<br />
Funciones relacionadas:<br />
tzset.<br />
asctime, ctime, gmtime, localtime,<br />
void getdate(struct date *f);<br />
Obtiene la fecha <strong>de</strong>l sistema. Los componentes se almacenan en la<br />
estructura date <strong>de</strong>finida en dos.h.<br />
struct date {<br />
int da_year; // año actual (1980-2099)<br />
char da_day; // dia mes (1-31)<br />
char da_mon; // mes (1-12)<br />
};<br />
dostounix<br />
#inclu<strong>de</strong> <br />
struct date fecha;<br />
getdate(&fecha);<br />
long dostounix(struct date *f, struct time *h);<br />
Convierte la fecha y hora DOS (<strong>de</strong>vuelta por getdate y gettime) en<br />
formato UNIX.<br />
time_t t;<br />
struct time dos_hora;<br />
struct date dos_fecha;<br />
gatdate(&Dos_hora);<br />
gettime(&dos_fecha);<br />
t = dostounix(&dos_fecha, &dos_hora);<br />
Funciones relacionadas: ctime, gatdate, gettime.<br />
Funciones relacionadas: dostounix, gettime, setdate, settime.<br />
gettime<br />
void gettime(struct time *t);<br />
#inclu<strong>de</strong> <br />
Obtiene la hora actual <strong>de</strong>l sistema. Los componentes <strong>de</strong> la hora se almacenan<br />
en la estructura time <strong>de</strong>finida en dos.h.<br />
struct time {<br />
unsigned char ti_min // minutos (0-59)
BIBLIOTECA DE FUNCIONES ESTÁNDAR <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0 629<br />
unsigned char ti_hour // horas (0-23)<br />
unsigned char ti_hund // centésimas <strong>de</strong> segundo (0-99)<br />
unsigned char ti_sec // segundos (0-59)<br />
};<br />
setdate<br />
void setdate(struct date *f);<br />
#inclu<strong>de</strong> <br />
struct time hora;<br />
gettime(&hora);<br />
Funciones relacionadas: dostounix, getdate, setdate, settime.<br />
gmtime<br />
struct tm *gmtime (const time_t *hora);<br />
#inclu<strong>de</strong> <br />
Convierte la fecha y hora en el tiempo medio <strong>de</strong> Greenwich (GMT)<br />
(año, mes, día, hora, minutos, segundos y otros campos). Véase struct tm<br />
en asctime.<br />
Cambia la fecha actual <strong>de</strong>l sistema. Los componentes <strong>de</strong> la fecha (día,<br />
mes. Año) se especifican en los campos <strong>de</strong> la estructura date.<br />
struct date {<br />
int da_year; // año actual<br />
char da_day; // día mes<br />
char da_mon; // mes, 1 para enero, 2...<br />
};<br />
En Visual <strong>C++</strong> la función equivalente es _dos_setdate.<br />
setdate(&fecha);<br />
Funciones relacionadas: getdate, gettime, settime, dostounix.<br />
ahora = gmtime(&hoy);<br />
Funciones relacionadas: asctime, ctime, ftime, localtime, time.<br />
settime<br />
void settime(struct time *h);<br />
#inclu<strong>de</strong> <br />
localtime<br />
struct tm *localtime(const time_t *hora);<br />
#inclu<strong>de</strong> <br />
Convierte una fecha y hora en varios campos <strong>de</strong> una estructura <strong>de</strong> tipo<br />
tm. Véase struct tm en asctime.<br />
Cambia la hora actual <strong>de</strong>l sistema. Los componentes <strong>de</strong> la hora —hora,<br />
minutos y segundos— se <strong>de</strong>ben cargar en los campos apropiados <strong>de</strong> la<br />
estructura time <strong>de</strong>finida en dos.h. Véase gettime.<br />
settime(&hora);<br />
Funciones relacionadas: dostounix, gatdate, gettime, setdate.<br />
tiempoactual = localtime(&ahora);<br />
Funciones relacionadas: asctime, gmtime, time.<br />
stime<br />
int stime(time_t *t);<br />
#inclu<strong>de</strong> <br />
mktime<br />
time_t mktime(struct tm *h);<br />
#inclu<strong>de</strong> <br />
Convierte la hora local a un valor <strong>de</strong> calendario. Véase struct tm en<br />
asctime.<br />
Funciones relacionadas: asctime, gmtime, localtime, time.<br />
Establece la fecha y hora <strong>de</strong>l sistema al valor contenido en la posición<br />
cuya dirección está en el argumento t.<br />
time_t horasis;<br />
horasis = time(NULL);<br />
stime(&horasis);<br />
printf(“segundos <strong>de</strong>s<strong>de</strong> 1/1/70 %ld”, horasis);<br />
Funciones relacionadas: dostounix.
630 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
strftime<br />
#inclu<strong>de</strong> <br />
Convierte a formato DOS un valor <strong>de</strong> hora en el formato UNIX.<br />
size_t strftime(char *cad, size_t maxlon,<br />
const char *formato, const struct tm *t);<br />
Convierte un puntero en una estructura tm en una ca<strong>de</strong>na cad (con una<br />
longitud máxima <strong>de</strong> n), utilizando f para dar formato a la ca<strong>de</strong>na. El formato<br />
es similar a printf().<br />
horaseg = time(NULL);<br />
horaactual = localtime(&horaseg);<br />
strftime(buffer, 80, “%A %B %d 19%y:I:%M, horaactual);<br />
Funciones relacionadas:<br />
time.<br />
time<br />
time_t time(time_t *h);<br />
asctime, ctime, gmtime, localtime,<br />
#inclu<strong>de</strong> <br />
Proporciona el tiempo <strong>de</strong>l sistema en segundos <strong>de</strong>s<strong>de</strong> las 00:00:00 <strong>de</strong><br />
1/1/1970 tiempo GMT.<br />
time(&hora);<br />
tzset<br />
void tzset(void);<br />
#inclu<strong>de</strong> <br />
Establece las variables <strong>de</strong> entorno horarios TZ; asigna valores a las<br />
variables globales timezone, daylight y tzname.<br />
tzset();<br />
printf(“Luz <strong>de</strong> verano = %d\n”, daylight);<br />
printf(“zona horario = %ld\n”, timezone);<br />
Funciones relacionadas:<br />
time.<br />
unixtodos<br />
asctime, ftime, gmtime, localtime,<br />
#inclu<strong>de</strong> <br />
void unixtodos(long time, struct date *f, struct time *h);<br />
tnixtodos(t_unix, &d_dos, ft_dos);<br />
Funciones relacionadas: getdate, gettime, time, setdate, settime.<br />
F.7.<br />
FUNCIONES DE CONTROL DE DIRECTORIOS<br />
MS-DOS, al igual que UNIX, utiliza un sistema <strong>de</strong> archivos jerárquico que<br />
permite al usuario organizar sus archivos en directorios y subdirectorios.<br />
Las <strong>funciones</strong> <strong>de</strong> control <strong>de</strong> directorios en Borland <strong>C++</strong> proporcionan las<br />
herramientas necesarias para crear, modificar, mover y eliminar directorios<br />
<strong>de</strong>s<strong>de</strong> sus programas C. Las <strong>funciones</strong> <strong>de</strong> manipulación <strong>de</strong> directorios resi<strong>de</strong>n<br />
en el archivo <strong>de</strong> cabecera dir.h.<br />
chdir<br />
int chdir(const char *camino);<br />
#inclu<strong>de</strong> <br />
Cambia el directorio <strong>de</strong> trabajo actual al directorio especificado en el<br />
argumento camino. La función <strong>de</strong>vuelve un 0 si tiene éxito; en caso contrario,<br />
<strong>de</strong>vuelve un valor <strong>de</strong> –1 para asignar el error. Cuando se produce un<br />
error, la variable global errno toma el valor ENOENT (camino o archivo no<br />
encontrado).<br />
if(chdir(\\)) {<br />
perror(“chdir()”);<br />
exit(1);<br />
}<br />
Funciones relacionadas: mkdir, rmdir, setdisk, system.<br />
findfirst<br />
#inclu<strong>de</strong> <br />
int findfirst(const char *camino, struct ffblk *ffblk, int atrib);<br />
Busca en un directorio <strong>de</strong> disco hasta encontrar el primer archivo cuyo<br />
nombre y atributos se correspon<strong>de</strong>n con los valores especificados. El formato<br />
<strong>de</strong> la estructura ffblk es:<br />
struct ffblk {<br />
char ff_reserved[21];<br />
// reservada por DOS
BIBLIOTECA DE FUNCIONES ESTÁNDAR <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0 631<br />
char ff_atrib;<br />
int ff_ftime;<br />
int ff_date;<br />
long ff_fsize;<br />
char ff_name[13];<br />
};<br />
// encontrado atributo<br />
// hora archivo<br />
// fecha archivo<br />
// tamaño archivo<br />
// encontrado nombre <strong>de</strong> archivo<br />
La variable attrib viene <strong>de</strong>finida en el archivo <strong>de</strong> cabecera y<br />
pue<strong>de</strong> ser igual a uno <strong>de</strong> estos valores:<br />
FA_RDONLY<br />
FA_HIDDEN<br />
FA_SYSTEM<br />
FA_LABEL<br />
FA_DIREC<br />
FA_ARCH<br />
struct ffblk ffblk;<br />
int t;<br />
t = findfirst(“*.*”, &ffblk,0);<br />
Funciones relacionadas: findnext.<br />
findnext<br />
Archivo <strong>de</strong> sólo lectura.<br />
Archivo oculto.<br />
Archivo <strong>de</strong>l sistema.<br />
Etiqueta <strong>de</strong> volumen.<br />
Directorio.<br />
Bit <strong>de</strong> archivo activado.<br />
int findnext(struct ffblk *ffblk);<br />
#inclu<strong>de</strong> <br />
findnext continúa la búsqueda <strong>de</strong> findfirst(). findnext llama a<br />
la función 4Fh <strong>de</strong> DOS para encontrar el siguiente archivo cuyo nombre y<br />
atributos son idénticos a los dados en la llamada a la función findfirst().<br />
fnsplit<br />
#inclu<strong>de</strong> <br />
void fnsplit(const char *camino, char *u, char *dir,<br />
char *nombrearch, char *ext);<br />
Separa un nombre <strong>de</strong> camino completo en sus componentes: letra <strong>de</strong> la<br />
unidad (u), camino <strong>de</strong>l directorio, nombre <strong>de</strong>l archivo y extensión <strong>de</strong>l archivo<br />
(ext).<br />
h = fnsplit(camino, unidad, dir, nomarch, ext);<br />
Funciones relacionadas: fnmerge.<br />
getcurdir<br />
int getcurdir(int u, char *dir);<br />
#inclu<strong>de</strong> <br />
Obtiene el directorio <strong>de</strong> trabajo actual en una unidad específica. El<br />
número <strong>de</strong> la unidad (u) 0 indica la unidad actual por omisión, 1 significa<br />
unidad A, 2 unidad B, etc. La función <strong>de</strong>vuelve un cero si tiene éxito, en<br />
caso <strong>de</strong> error <strong>de</strong>vuelve –1.<br />
getcurdir(3, cuentas);<br />
Funciones relacionadas: getcwd, getdisk.<br />
findnext(&filefinfo);<br />
Funciones relacionadas: findfirst.<br />
getcwd<br />
char *getcwd(char *camino, int numcar);<br />
#inclu<strong>de</strong> <br />
fnmerge<br />
#inclu<strong>de</strong> <br />
void fnmerge(char *camino, const char *u, const char *dir,<br />
const *nombrearch, const char *ext);<br />
Crea un nombre <strong>de</strong> camino completo compuesto <strong>de</strong> una letra <strong>de</strong> la unidad<br />
(u), camino <strong>de</strong>l directorio (dir), nombre <strong>de</strong> archivo (nombrearch) y<br />
extensión <strong>de</strong>l archivo (ext).<br />
fnmerge(camino, “c:”, \\aux\\”,”<strong>de</strong>mo”,”.dat”);<br />
Funciones relacionadas: fnsplit.<br />
getcwd obtiene el nombre <strong>de</strong> camino completo <strong>de</strong>l directorio <strong>de</strong> trabajo<br />
actual, incluyendo el nombre <strong>de</strong> la unidad. El argumento numcar indica<br />
a getcwd el máximo número <strong>de</strong> caracteres que el buffer camino pue<strong>de</strong> contener.<br />
La función getcwd es útil para obtener el nombre <strong>de</strong>l directorio actual<br />
y guardarlo. Si su programa cambia los directorios <strong>de</strong> trabajo durante su ejecución,<br />
pue<strong>de</strong> utilizar el nombre guardado para restaurar el directorio <strong>de</strong> trabajo<br />
actual antes <strong>de</strong> terminar.<br />
getcwd(cuentas, 80)<br />
Funciones relacionadas: chdir.
632 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
getdisk<br />
#inclu<strong>de</strong> <br />
Funciones relacionadas: chdir, rmdir.<br />
int getdisk(void);<br />
La función getdisk obtiene el valor entero que representa la unidad<br />
actual (0, unidad A; 1, unidad B...)<br />
int unidad;<br />
clscr();<br />
unidad = getdisk();<br />
Funciones relacionadas: setdisk.<br />
mktemp<br />
#inclu<strong>de</strong> <br />
char *mktemp(char *plantilla);<br />
Crea un nombre <strong>de</strong> archivo a partir <strong>de</strong> una plantilla. Devuelve un puntero<br />
al nombre <strong>de</strong>l archivo si tiene éxito y nulo en caso <strong>de</strong> error.<br />
mktemp(nombre);<br />
mdir<br />
#inclu<strong>de</strong> <br />
searchpath<br />
#inclu<strong>de</strong> <br />
int rmdir(const char *camino);<br />
Elimina el directorio escrito por la variable camino, siempre que el<br />
directorio esté vacío, no sea el directorio raíz y no sea el directorio <strong>de</strong> trabajo<br />
rmdir(); <strong>de</strong>vuelve 0 si la operación <strong>de</strong> borrado tiene éxito; si se produce<br />
un error, el valor <strong>de</strong>vuelto es –1 y la variable global errno se fija a uno<br />
<strong>de</strong> los siguientes valores:<br />
EACCES Permiso <strong>de</strong>negado.<br />
ENOENT Camino archivo no encontrado.<br />
Esta función es similar a RMDIR o RD <strong>de</strong> MS-DOS.<br />
rmdir(“C:\\PRUEBAS”); Supresión <strong>de</strong> directorio PRUEBAS<br />
Funciones relacionadas: chdir, mkdir.<br />
char searchpath(const char *nombre);<br />
Busca un archivo específico en una lista <strong>de</strong> directorios, incluyendo el<br />
directorio <strong>de</strong> trabajo actual y los <strong>de</strong>finidos en la variable <strong>de</strong> entorno PATH.<br />
Si el archivo se encuentra, se <strong>de</strong>vuelve un puntero al nombre <strong>de</strong>l camino <strong>de</strong>l<br />
archivo; en caso contrario, se <strong>de</strong>vuelve NULL.<br />
buffer = searchpath(“BC.EXE”);<br />
Localizar el archivo AUTOEXEC.BAT en los directorios <strong>de</strong>finidos en la<br />
variable <strong>de</strong> entorno PATH.<br />
buffer = searchpath(“autoexec.bat”);<br />
Funciones relacionadas: getenv, putenv.<br />
mkdir<br />
#inclu<strong>de</strong> <br />
setdisk<br />
#inclu<strong>de</strong> <br />
int mkdir(const char *camino);<br />
Crea un directorio con un nombre <strong>de</strong> camino especificado. Funciona<br />
igual que la or<strong>de</strong>n MKDIR o MD <strong>de</strong> DOS. Devuelve 0 si el directorio se ha<br />
creado con éxito o –1 si se produce un error; en este caso, la variable global<br />
errno toma el valor EACCES (permiso <strong>de</strong>negado) o ENOENT (nombre <strong>de</strong><br />
camino no válido).<br />
EACCES<br />
ENOENT<br />
Permiso <strong>de</strong>negado.<br />
Camino no encontrado.<br />
resultado = mkdir(“PRUEBAS”);<br />
// crea el directorio PRUEBAS<br />
int setdisk(int unidad);<br />
Cambia a una nueva unidad por omisión. El valor <strong>de</strong> la unidad (unidad)<br />
es un entero.<br />
Unidad A<br />
B:<br />
C:<br />
D:<br />
...<br />
nuevaunidad = setdisk(3); / nueva unidad actual es C:<br />
Funciones relacionadas: getdisk
BIBLIOTECA DE FUNCIONES ESTÁNDAR <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0 633<br />
F.8.<br />
FUNCIONES DE CONTROL DE PROCESOS<br />
atexit<br />
#inclu<strong>de</strong> <br />
Un proceso es un programa ejecutable en memoria y su entorno asociado.<br />
Cada vez que se ejecuta un programa se crea un proceso.<br />
En resumen, un proceso es un programa que se está ejecutando por el<br />
sistema operativo. Consta <strong>de</strong>l código <strong>de</strong>l programa y <strong>de</strong> datos, a<strong>de</strong>más <strong>de</strong><br />
información relativa al proceso, tales como número <strong>de</strong> archivos abiertos.<br />
Siempre que se ejecuta un programa al nivel <strong>de</strong>l sistema operativo se arranca<br />
un proceso.<br />
Las <strong>funciones</strong> <strong>de</strong> control <strong>de</strong> proceso permiten arrancar, <strong>de</strong>tener y gestionar<br />
procesos <strong>de</strong>s<strong>de</strong> <strong>de</strong>ntro <strong>de</strong> un programa. La mayoría <strong>de</strong> las <strong>funciones</strong><br />
<strong>de</strong> control se <strong>de</strong>claran en el archivo <strong>de</strong> cabecera process.h; otros archivos<br />
<strong>de</strong> cabecera que contienen <strong>funciones</strong> <strong>de</strong> control <strong>de</strong> proceso y <strong>de</strong>l entorno son<br />
locale.h, signal.h, setjmp.h y stdlib.h.<br />
abort<br />
void abort(void);<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
Termina la ejecución <strong>de</strong>l programa actual y <strong>de</strong>vuelve un código <strong>de</strong><br />
error (3).<br />
if (argc 1) {<br />
printf(“Faltan argumentos!\n”)<br />
abort()<br />
}<br />
Funciones relacionadas : exit, _exit, raise, signal, spaw.<br />
int atexit(void(*func)(void));<br />
Procesa la función especificada al salir.<br />
atexit(segundo);<br />
Funciones relacionadas: abort, exit, _exit.<br />
exec(familia)<br />
#inclu<strong>de</strong> <br />
int excel(char *camino, char *arg0,...,NULL);<br />
int execle(char *camino, char *arg0,..., *argn, NULL, char **env);<br />
int execlp(char *camino, char *arg0, arg1,...,NULL);<br />
int execlpe(char *camino, char *arg0,...argn, NULL, char **env);<br />
int execv(char *camino, char argv[]);<br />
int execve(char *camino, char argv[], char **env);<br />
int execvp(char *camino, char *argv[]);<br />
int execvpe(char *camino, char *argv[], char **env);<br />
Cargan y ejecutan un proceso hijo en la memoria actualmente ocupada<br />
por su código <strong>de</strong>l programa. Las <strong>funciones</strong> exec crean un proceso hijo que<br />
carga y ejecuta el programa especificado por el argumento camino.<br />
execlo(“hijo.exe”, hijo.exe”, “Uno, “Dos”, NULL);<br />
execv(“hijo.exe”, argv);<br />
assert<br />
#inclu<strong>de</strong> <br />
Funciones relacionadas: abort, atexit, exit, _exit, fpreset, spawn.<br />
void assert(int expresión);<br />
Imprime un mensaje <strong>de</strong> error e interrumpe el programa si expresión es<br />
falsa (0).<br />
assert(string != NULL;<br />
assert(*string != ´\0´);<br />
assert(strlen(string) < 2);<br />
Funciones relacionadas: abort, raise, signal.<br />
exit<br />
void exit(int estado);<br />
#inclu<strong>de</strong> <br />
Termina un programa. Antes <strong>de</strong> terminar, se cierran todos los archivos,<br />
se escribe la salida a través <strong>de</strong>l buffer y se llama a cualquier función exit<br />
registrada. estado representa el estado <strong>de</strong> salida <strong>de</strong>l programa; 0, salida<br />
normal; distinto <strong>de</strong> cero, indica un error.<br />
exit(0);
634 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
Funciones relacionadas: abort, atexit, ´exit, exit, ´fpreset,<br />
spawn, system.<br />
Obtiene información <strong>de</strong>tallada sobre formatos monetarios y numéricos<br />
<strong>de</strong> diferentes países.<br />
_exit<br />
void _exit(int estado);<br />
#inclu<strong>de</strong> <br />
p_lconv = localeconv();<br />
Funciones relacionadas: setlocale.<br />
Termina inmediatamente el proceso actual sin hacer otras operaciones<br />
auxiliares (como cierre <strong>de</strong> archivos).<br />
_exit(0)<br />
Funciones relacionadas: exit.<br />
getenv<br />
char *getenv(const char *nomvar);<br />
#inclu<strong>de</strong> <br />
Obtiene la <strong>de</strong>finición <strong>de</strong> una variable <strong>de</strong> la tabla <strong>de</strong> entorno <strong>de</strong>l proceso.<br />
Utiliza la variable global environ para localizar la lista <strong>de</strong> las variables<br />
<strong>de</strong> entorno y, a continuación, busca una entrada en la lista correspondiente<br />
a nomvar.<br />
varlib = getenv(“LIB”);<br />
Funciones relacionadas: putenv.<br />
longjmp<br />
void longjmp(jmp_buf env, int valor);<br />
#inclu<strong>de</strong> <br />
Restaura el estado <strong>de</strong> la pila y la ejecución local anteriormente grabada<br />
en env por setjmp.<br />
longjmp(plaza, 3);<br />
Funciones relacionadas: setjmp.<br />
perror<br />
void perror(const char *ca<strong>de</strong>na);<br />
#inclu<strong>de</strong> <br />
Imprime un mensaje <strong>de</strong> error <strong>de</strong>l sistema en el flujo st<strong>de</strong>rr. El argumento<br />
ca<strong>de</strong>na se imprime primero, seguido por dos puntos; a continuación,<br />
el mensaje <strong>de</strong> error correspondiente al valor actual <strong>de</strong> la variable global<br />
errno y, finalmente, un carácter <strong>de</strong> nueva línea. Si ca<strong>de</strong>na es un puntero<br />
nulo o un puntero a una ca<strong>de</strong>na nula, perror imprime sólo el mensaje <strong>de</strong><br />
error <strong>de</strong>l sistema.<br />
getpid<br />
unsigned getpid(void)<br />
#inclu<strong>de</strong> <br />
perror(“Error <strong>de</strong> cierre <strong>de</strong> archivos”);<br />
Funciones relacionadas: _strerror, strerror.<br />
Obtiene el ID <strong>de</strong> proceso <strong>de</strong> un programa. Está disponible en sistemas<br />
UNIX.<br />
printf(“PID:%X\n”,getpid());<br />
putenv<br />
int putenv(const char *ca<strong>de</strong>na);<br />
#inclu<strong>de</strong> <br />
Funciones relacionadas: getpsp.<br />
localeconv<br />
struct lconv *localeconv(void);<br />
#inclu<strong>de</strong> <br />
Crea nuevas variables <strong>de</strong> entorno o modifica los valores <strong>de</strong> las variables<br />
<strong>de</strong> entorno existentes.<br />
if(putenv(argv[1] == -1)<br />
Funciones relacionadas: getenv.
BIBLIOTECA DE FUNCIONES ESTÁNDAR <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0 635<br />
raise<br />
int raise(int señal);<br />
#inclu<strong>de</strong> <br />
Envía una señal al programa en ejecución. Crea una condición <strong>de</strong><br />
excepción correspondiente al número señal. Existen diferentes constantes,<br />
por ejemplo, SIGABRT (terminación anormal).<br />
printf(“prueba <strong>de</strong> raise\n”);<br />
raise(SIGABRT);<br />
Funciones relacionadas: abort, signal.<br />
setjmp<br />
int setjmp(jmp_buf env);<br />
#inclu<strong>de</strong> <br />
Guarda el estado actual <strong>de</strong>l programa (el entorno <strong>de</strong> la pila) antes <strong>de</strong> llamar<br />
a otra función. Este entorno pue<strong>de</strong> ser restaurado por una llamada a<br />
longjmp, realizando el efecto <strong>de</strong> un goto no local.<br />
if(setjmp(env) != 0) printf(“valor <strong>de</strong> longjmp\n”);<br />
Funciones relacionadas: longjmp.<br />
int spawnle(int modo, char *camino, char *arg0, char *arg1,...,NULL,<br />
char **envp[]);<br />
int spawnlp(int modo, char *camino, char *arg0, char *arg1,...,NULL);<br />
int spawnlpe(int modo, char *camino, char *arg0, char *arg1,...,NULL,<br />
char **envp[]);<br />
int spawnv(int modo, char *camino, char *argv[]);<br />
int spawnve(int modo, char *camino, char /argv[], char *envp[]);<br />
int spawnvp(int modo, char *camino, char *argv[]);<br />
int spawnvpe(int modo, char *camino, char *argv[], char *envp[]);<br />
La familia <strong>de</strong> <strong>funciones</strong> spawn crea y ejecuta un nuevo proceso hijo.<br />
Debe haber memoria suficiente para cargar y ejecutar el proceso hijo.<br />
spawnlpe(P_WAIT, “hijo.exe”, “hijo.exe”, “spawnlpe”, buf,<br />
NULL, env);<br />
Funciones relacionadas: exec.<br />
F.9.<br />
FUNCIONES DE CONVERSIÓN DE DATOS<br />
Las <strong>funciones</strong> <strong>de</strong> conversión <strong>de</strong> tipos <strong>de</strong> datos sirven para crear un puente <strong>de</strong><br />
unión entre los dos estilos <strong>de</strong> representación <strong>de</strong> números: la ca<strong>de</strong>na <strong>de</strong> texto<br />
legible por los humanos y el formato binario legible por las máquinas. Las<br />
<strong>funciones</strong> <strong>de</strong> conversión son i<strong>de</strong>ales para convertir argumentos <strong>de</strong> líneas <strong>de</strong><br />
ór<strong>de</strong>nes <strong>de</strong> su representación <strong>de</strong> ca<strong>de</strong>na al formato interno.<br />
signal<br />
void (*signal(int sig, void (*func) (int))) (int);<br />
#inclu<strong>de</strong> <br />
atof()<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
Establece tratamiento <strong>de</strong> señales <strong>de</strong> interrupción. La función signal permite<br />
a un proceso elegir uno <strong>de</strong> los diferentes modos <strong>de</strong> manipular una señal<br />
<strong>de</strong> interrupción <strong>de</strong>l sistema operativo.<br />
signal(SIGINT, SIG_IGN);<br />
Funciones relacionadas: abort, _control87, exit, longjmp, raise,<br />
setjmp.<br />
spawn (<strong>funciones</strong>)<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
int spawnl(int modo, char *camino, char *arg0, char *arg1,...,NULL);<br />
double atof(const char *ca<strong>de</strong>na);<br />
La función atof() convierte el argumento ca<strong>de</strong>na en un valor <strong>de</strong> doble<br />
precisión. La ca<strong>de</strong>na <strong>de</strong>be tener el siguiente formato:<br />
[blanco][signo][ddd][.]]ddd][exponente][signo][ddd]<br />
opcional<br />
blancos o<br />
tabulaciones<br />
dígitos <strong>de</strong>cimales<br />
e/E<br />
La conversión termina cuando aparece el primer carácter no reconocible<br />
o cuando se encuentra un carácter nulo (´\0´).
636 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
double x;<br />
char *cad_dbl = “200-85”;<br />
...<br />
x = atof(cad_dbl); // convierte la ca<strong>de</strong>na “200.85”<br />
a real<br />
Funciones relacionadas: atoi, atol, ecvt, fcvt, gcvt, scanf,<br />
strtod.<br />
La conversión <strong>de</strong> caracteres <strong>de</strong> la ca<strong>de</strong>na hasta que se encuentre el primer<br />
carácter no reconocible o el carácter nulo (‘\0’).<br />
long int i;<br />
char cad_ent = “9876543”;<br />
...<br />
i = atol(cad_ent);<br />
// convierte ca<strong>de</strong>na “9876543” a entero<br />
// largo.<br />
atoi<br />
int atoi (const char *ca<strong>de</strong>na)<br />
#inclu<strong>de</strong> <br />
Funciones relacionadas: atof, atoi, itoa, ltoa, scanf, strtod,<br />
strtol, strtoul, ultoa.<br />
La función atoi() convierte el argumento ca<strong>de</strong>na en un valor entero.<br />
La ca<strong>de</strong>na <strong>de</strong>be tener el siguiente formato:<br />
[espacio en blanco][signo][ddd]<br />
espacio o tabulación<br />
opcional<br />
dígitos <strong>de</strong>cimales<br />
La conversión termina cuando se encuentra un carácter no reconocible<br />
(carácter nulo, ‘\0’, punto <strong>de</strong>cimal o una letra). Si no pue<strong>de</strong> convertir la<br />
ca<strong>de</strong>na <strong>de</strong>vuelve nulo.<br />
int i;<br />
char *cad_ent =123;<br />
...<br />
i = atoi(cad_ent);// convierte la ca<strong>de</strong>na “123” al entero 123<br />
Funciones relacionadas: atof, atol, itoa, ltoa, scanf, ultoa.<br />
atol<br />
long atol(const char *ca<strong>de</strong>na);<br />
#inclu<strong>de</strong> <br />
Convierte el argumento ca<strong>de</strong>na en un valor entero largo. La ca<strong>de</strong>na <strong>de</strong>be<br />
tener el formato:<br />
[espacio en blanco][signo][ddd]<br />
blancos y tabulaciones<br />
opcional<br />
dígitos <strong>de</strong>cimales<br />
ecvt<br />
#inclu<strong>de</strong> <br />
char *ecvt(double valor, int n, int *<strong>de</strong>c, int *signo);<br />
La función ecvt() convierte un argumento <strong>de</strong> valor doble precisión en<br />
una ca<strong>de</strong>na con n dígitos. Si valor tiene más <strong>de</strong> n dígitos, los dígitos inferiores<br />
se truncan. <strong>de</strong>c es un puntero a un entero en don<strong>de</strong> se <strong>de</strong>vuelve la<br />
posición <strong>de</strong>l punto <strong>de</strong>cimal; signo es un puntero a un entero don<strong>de</strong> se<br />
<strong>de</strong>vuelve el signo (cero, positivo; en los restantes casos, negativo).<br />
p_buffer = ecvt(valor, exactitud, &<strong>de</strong>c, &signo);<br />
Funciones relacionadas: atof, fcvt, gcvt, printf, sprintf, itoa,<br />
ltoa, ultoa.<br />
fcvt<br />
#inclu<strong>de</strong> <br />
char *fcvt(double valor, int n, int *<strong>de</strong>c, int *signo);<br />
Al igual que la función ecvt, fcvt convierte el argumento valor <strong>de</strong><br />
doble precisión en una ca<strong>de</strong>na <strong>de</strong> n dígitos. Si el número <strong>de</strong> dígitos <strong>de</strong> valor<br />
exce<strong>de</strong> a n, el exceso <strong>de</strong> dígitos se trunca. Si hay menos dígitos que n la<br />
ca<strong>de</strong>na se rellena con ceros. fcvt se diferencia <strong>de</strong> ecvt en el modo <strong>de</strong> tratar<br />
los dígitos significativos. ecvt() busca un número total <strong>de</strong> dígitos,<br />
mientras que fcvt() busca el número <strong>de</strong> dígitos a la <strong>de</strong>recha <strong>de</strong>l puntero<br />
<strong>de</strong>cimal.<br />
ca<strong>de</strong>na = fcvt(valor, exactitud, %oposición_d, &signo);<br />
Funciones relacionadas: atof, ecvt, gcvt, itoa, ltoa, printf,<br />
sprintf, ultoa.
BIBLIOTECA DE FUNCIONES ESTÁNDAR <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0 637<br />
gcvt<br />
#inclu<strong>de</strong> <br />
strtod<br />
#inclu<strong>de</strong> stdlib.h><br />
char *gcvt(double valor, int ndig, char, *buf);<br />
La función gcvt() convierte el argumento valor <strong>de</strong> doble precisión en<br />
una ca<strong>de</strong>na <strong>de</strong> caracteres que se almacena en el buffer cuya dirección se da<br />
en el argumento buf. Se <strong>de</strong>be asignar bastante espacio en el buffer para contener<br />
todos los dígitos <strong>de</strong> la ca<strong>de</strong>na convertida y el carácter nulo <strong>de</strong> terminación<br />
(‘\0’).<br />
gcvt(valor, digitos, ca<strong>de</strong>na);<br />
Funciones relacionadas: atof, ecvt, fcvt, itoa, ltoa, printf,<br />
sprintf, ultoa.<br />
itoa<br />
char *itoa(int valor, char *cad, int base);<br />
#inclu<strong>de</strong> stdlib.h><br />
La función itoa() convierte el argumento entero valor en una ca<strong>de</strong>na<br />
<strong>de</strong> caracteres utilizando el argumento base, como base <strong>de</strong> un sistema <strong>de</strong><br />
numeración (2 a 36). Debe existir bastante espacio en cad para contener 17<br />
caracteres, itoa() <strong>de</strong>vuelve un puntero a la ca<strong>de</strong>na cad.<br />
itoa(32, buffer, 16); // buffer contendrá “20”, ya que 32 entero<br />
// equivale a 20 en hexa<strong>de</strong>cimal<br />
Funciones relacionadas: atoi, atol, itoa, ultoa.<br />
double strtod(const char *cad, char **p);<br />
La función strtod() convierte la ca<strong>de</strong>na cad en un valor <strong>de</strong> doble<br />
precisión. La ca<strong>de</strong>na <strong>de</strong>be tener el formato<br />
[blanco][signo][ddd][.][exponente][signo][ddd]<br />
blanco/<br />
tabulación<br />
+, - d, D, e, E<br />
dígitos <strong>de</strong>cimales<br />
strtod() <strong>de</strong>vuelve el valor <strong>de</strong> doble precisión y cero si no se produce la<br />
conversión. La conversión se termina con el primer carácter no reconocible.<br />
Aplicación: Convertir la ca<strong>de</strong>na “843899.567” a un valor <strong>de</strong> coma flotante<br />
double.<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
main()<br />
{<br />
double x;<br />
char *num_flt = “843899.567”:<br />
char *p;<br />
x = strtod(num_flt, &p);<br />
printf(“x = %f\n”,x);<br />
}<br />
Funciones relacionadas: atof, printf, scanf, strtol, strtoul.<br />
ltoa<br />
char *ltoa(long valor, char * cad, int base);<br />
#inclu<strong>de</strong> <br />
La función ltoa() convierte el argumento entero largo valor en una<br />
ca<strong>de</strong>na <strong>de</strong> caracteres que utiliza el argumento base como base <strong>de</strong> un sistema<br />
<strong>de</strong> numeración. Como un entero largo ocupa 32 bits en base 2, la ca<strong>de</strong>na<br />
pue<strong>de</strong> ocupar 33 bytes con el carácter nulo <strong>de</strong> terminación. Debe haber<br />
bastante espacio para contener 33 bytes. ltoa() <strong>de</strong>vuelve un puntero a cad.<br />
long valor = 99288377L<br />
ltoa(valor, ca<strong>de</strong>na, 30);<br />
Funciones relacionadas: atoi, atol, itoa, ultoa.<br />
strtol<br />
long strtol(const char *cad, char **p, int b);<br />
#inclu<strong>de</strong> <br />
La función strtol() convierte una ca<strong>de</strong>na cad en un valor entero largo.<br />
La ca<strong>de</strong>na (pue<strong>de</strong> contener hasta 33 caracteres) <strong>de</strong>be tener el formato:<br />
[espacio en blanco][signo][0][x|X][ddd]<br />
+, - dígitos <strong>de</strong>cimales<br />
hexa<strong>de</strong>cimal<br />
blancos y tabulaciones octal
638 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
La conversión se termina con el primer carácter no reconocible. Si se<br />
produce un error <strong>de</strong> <strong>de</strong>sbordamiento (positivo o negativo) la variable errno<br />
se establece al valor <strong>de</strong> la macro ERANGE.<br />
Aplicación. Convertir la ca<strong>de</strong>na “9876” en valor entero.<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
main()<br />
{<br />
int base = 10;<br />
long int i;<br />
char *cad_ent = “9876”;<br />
char *ptrcad;<br />
i = strtol(cad_ent, &ptrcad, base);<br />
printf(“i = %ld\n”, i);<br />
}<br />
Funciones relacionadas: atoi, atof, atol, ltoa, strtoul.<br />
strtoul<br />
#inclu<strong>de</strong> <br />
unsigned long strtoul(const char *cad, char **p, int base);<br />
Convierte una ca<strong>de</strong>na <strong>de</strong> caracteres a un entero largo sin signo en la<br />
base dada. La ca<strong>de</strong>na <strong>de</strong>be tener el formato:<br />
[espacio en blanco][0][x|X][ddd]<br />
octal<br />
blanco o tabulaciones<br />
dígitos <strong>de</strong>cimales<br />
hexa<strong>de</strong>cimal<br />
Si la base b es cero, strtoul utiliza el primer carácter <strong>de</strong> la ca<strong>de</strong>na para<br />
<strong>de</strong>terminar la base <strong>de</strong>l valor.<br />
La ca<strong>de</strong>na cad pue<strong>de</strong> contener hasta 33 caracteres, excluyendo el carácter<br />
<strong>de</strong> terminación nulo (´\0,). Si se produce un error <strong>de</strong> <strong>de</strong>sbordamiento,<br />
la variable errno se pone al valor <strong>de</strong> ERANTE.<br />
i = strtoul(cad_ent, &ptrfin, base);<br />
Funciones relacionadas: atol, ultoa, strtol.<br />
ultoa<br />
#inclu<strong>de</strong> <br />
char *ultoa(unsigned long valor, char *cad, int base);<br />
La función ultoa() toma valor en base b (entre 2 y 36) y lo convierte<br />
en una ca<strong>de</strong>na. Devuelve el puntero al principio <strong>de</strong> cad. No <strong>de</strong>vuelve código<br />
<strong>de</strong> error. cad pue<strong>de</strong> contener hasta 33 caracteres, excluyendo el carácter<br />
<strong>de</strong> terminación nulo (´\0´).<br />
ultoa(valor, buffer, base);<br />
Funciones relacionadas: itoa, ltoa.<br />
F.10.<br />
FUNCIONES DE ENTRADA/SALIDA<br />
Las <strong>funciones</strong> <strong>de</strong> E/S (Entrada/Salida, I/O, Input/Output) permiten leer y<br />
escribir datos entre archivos y dispositivos. En C no hay estructuras <strong>de</strong><br />
archivos pre<strong>de</strong>finidas, todos los datos se tratan como secuencias <strong>de</strong> bytes.<br />
La lista <strong>de</strong> <strong>funciones</strong> <strong>de</strong> E/S se han agrupado <strong>de</strong> acuerdo a las tareas específicas<br />
que realizan:<br />
1. Secuencias o flujos (stream).<br />
2. Bajo nivel.<br />
3. Consola y puertos.<br />
Funciones <strong>de</strong> flujos (stream)<br />
Las <strong>funciones</strong> <strong>de</strong> E/S tratan los datos como una secuencia o flujo <strong>de</strong> caracteres<br />
individuales. La elección a<strong>de</strong>cuada <strong>de</strong> las <strong>funciones</strong> disponibles permite<br />
procesar datos en tamaños y formatos diferentes, <strong>de</strong>s<strong>de</strong> caracteres in<strong>de</strong>pendientes<br />
a estructuras <strong>de</strong> datos complejos. La E/S por secuencia, o flujo,<br />
también proporciona acciones <strong>de</strong> taponamiento (buffering) que mejoran significativamente<br />
el rendimiento. Para utilizar los flujos, generalmente se<br />
<strong>de</strong>be incluir el archivo stdio.h.<br />
clearerr<br />
void clearerr(FILE *f);<br />
Reinicializa el indicador <strong>de</strong> error <strong>de</strong> un flujo f.<br />
clearerr(fichen);<br />
Funciones relacionadas: eof, feof, ferror, perror.<br />
#inclu<strong>de</strong>
BIBLIOTECA DE FUNCIONES ESTÁNDAR <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0 639<br />
fclose, fcloseall<br />
#inclu<strong>de</strong> <br />
fflush<br />
#inclu<strong>de</strong> <br />
int fclose(FILE *f);<br />
int fcloseall(void);<br />
Cierra un flujo (fclose) o cierra todos los flujos abierta (fcloseall)<br />
excepto stdin, stdout y st<strong>de</strong>rr. Se <strong>de</strong>vuelve el número <strong>de</strong> flujos cerrados<br />
y EOF si se produce un error.<br />
fcloseall();<br />
Funciones relacionadas: close, fdopen, fopen.<br />
int fflush(FILE *f);<br />
Limpia (vacía) un flujo. Los buffers se limpian automáticamente cuando<br />
están llenos, cuando se cierra el flujo, o cuando un programa termina normalmente<br />
sin cerrar el flujo.<br />
fflush(fp);<br />
Funciones relacionadas: fclose, flshall, fopen.<br />
fdopen<br />
FILE *fdopen(int handle, char *modo);<br />
#inclu<strong>de</strong> <br />
Abre un flujo utilizando un handle (entero <strong>de</strong>vuelto por las rutinas <strong>de</strong><br />
E/S <strong>de</strong> bajo nivel, tales como open, creat, dup y dup2); asocia una<br />
estructura <strong>de</strong> datos FILE con el archivo especificado por handle.<br />
p_datos = fdopen(handle, “rb”);<br />
Funciones relacionadas: fclose, fopen, fropen, open.<br />
fgetc<br />
int fgetc(FILE * f);<br />
#inclu<strong>de</strong> <br />
Lee un carácter <strong>de</strong> la posición actual <strong>de</strong>l archivo y, a continuación,<br />
incrementa esta posición.<br />
c = fgetc(fp)<br />
Funciones relacionadas: fgetchar, fputc, fputchar, getc, putc,<br />
putchar.<br />
feof<br />
#inclu<strong>de</strong> <br />
fgetchar<br />
#inclu<strong>de</strong> <br />
int feof(FILE *flujo);<br />
#int fgetchar(void);<br />
Comprueba el final <strong>de</strong> archivo <strong>de</strong> un flujo.<br />
feof(fichen);<br />
Funciones relacionadas: clearerr, fclose, rewind.<br />
Lee un carácter <strong>de</strong>l archivo stdin, normalmente el teclado.<br />
c = fgetchar();<br />
Funciones relacionadas: fgetc, fputc, fputchar, putc, putchar.<br />
ferror<br />
#inclu<strong>de</strong> <br />
int ferror(FILE *f);<br />
Verifica si se ha producido un error en un flujo f.<br />
ferror(fichen);<br />
Funciones relacionadas: clarerr, eof, feof, fopen, perror.<br />
fgetpos<br />
int fgetpos(FILE *flujo, fpos_t *p);<br />
#inclu<strong>de</strong> <br />
Obtiene y graba la posición actual <strong>de</strong>l archivo. fos_t es un tipo <strong>de</strong>finido<br />
en stdio.h.<br />
fgetpos(fp, &pos_archivo);
640 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
fgets<br />
char *fgets(char *cad, int n, FILE *f);<br />
#inclu<strong>de</strong> <br />
Lee una ca<strong>de</strong>na <strong>de</strong> un flujo (hasta que se encuentra \n, o el número<br />
máximo <strong>de</strong> caracteres especificados).<br />
if ((corriente2 = fopen(“datos”, “W+”)) == NULL<br />
printf(“el archivo..no se ha abierto \n”);<br />
Funciones relacionadas: fclose, fcloseall, fdopen, ferror,<br />
fileno, freopen, open, setmo<strong>de</strong>.<br />
fgets(cad<strong>de</strong>mo,80, fp);<br />
Funciones relacionadas: fputs, gets, puts.<br />
flushall<br />
int flushall(void);<br />
#inclu<strong>de</strong> stdio.h><br />
fileno<br />
int fileno(FILE *f);<br />
#inclu<strong>de</strong> <br />
Obtiene el mando o manejador (handle) <strong>de</strong>l archivo asociado con un<br />
flujo.<br />
fileno(stdin);<br />
Funciones relacionadas: fdopen, fopen.<br />
Vacía (limpia) todos los buffers asociados con los archivos abiertos.<br />
numvaciados = flushall();<br />
Funciones relacionadas: fclose, fflush.<br />
fprintf<br />
#inclu<strong>de</strong> <br />
int fprintf(FILE *f, const char *formato[arg,...]);<br />
Imprime datos con formato en un flujo.<br />
fopen<br />
#inclu<strong>de</strong> <br />
fprintf(f1,”El resultado es %f\n”,result);<br />
FILE *fopen(const char *f, const char *modo);<br />
Abre un archivo f. La ca<strong>de</strong>na <strong>de</strong> caracteres modo especifica el tipo <strong>de</strong><br />
acceso.<br />
Modo<br />
“r”<br />
“w”<br />
“a”<br />
“r+”<br />
“w+”<br />
“a+”<br />
“rb”<br />
“wb”<br />
“ab”<br />
“rb”<br />
“wb”<br />
“ab”<br />
Acción<br />
Abre para lectura.<br />
Abre un archivo vacío para escritura.<br />
Abre para escritura al final <strong>de</strong>l archivo (añadir).<br />
Abre para lectura/escritura.<br />
Abre un archivo vacío para lectura/escritura.<br />
Abre para lectura y añadir.<br />
Abre un archivo binario para lectura.<br />
Crea un archivo binario para escritura.<br />
Abre un archivo binario para añadir.<br />
Abre un archivo binario para lectura/escritura.<br />
Crea un archivo binario para la lectura/escritura.<br />
Abre o crea un archivo binario para lectura/escritura.<br />
Funciones relacionadas: cprintf, fscanf, printf, putc, sprintf.<br />
fputc<br />
int fputc(int c, FILE *f);<br />
#inclu<strong>de</strong> <br />
Escribe un carácter c en el flujo abierto para salida con buffer.<br />
fputc(*(p++), stdout);<br />
Funciones relacionadas: fgetc, fgetchar, fputchar, getc, getchar,<br />
putc.<br />
fputchar<br />
int fputchar(int c);<br />
#inclu<strong>de</strong>
BIBLIOTECA DE FUNCIONES ESTÁNDAR <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0 641<br />
Escribe el carácter c en stdout.<br />
fputchar(´q´);<br />
Funciones relacionadas: fgetc, fgetchar, gputc, getc, getchar.<br />
Lee datos con formato <strong>de</strong> un flujo.<br />
fscanf(flujo, “%s%f”, cad, &f);<br />
Funciones relacionadas: csanf, fprintf, scanf, sscanf.<br />
fputs<br />
#inclu<strong>de</strong> <br />
fseek<br />
#inclu<strong>de</strong> <br />
int fputs(const char *cad, FILE *f);<br />
int fseek(FILE *f, long <strong>de</strong>sp, int org);<br />
Escribe una letra cad en un flujo f. Devuelve el último carácter impreso,<br />
si hay error <strong>de</strong>vuelve EOF.<br />
Mueve el puntero <strong>de</strong>l archivo asociado con f a una nueva posición que<br />
está <strong>de</strong>splazada <strong>de</strong>sp bytes <strong>de</strong> org.<br />
fputs(“esto es una prueba”, f1);<br />
Origen<br />
Significado<br />
Funciones relacionadas fgets, gets, puts.<br />
fread<br />
#inclu<strong>de</strong> <br />
size_t fread(void *p, size_t t, size_t n, FILE *f);<br />
Lee n registros <strong>de</strong> t bytes en la memoria apuntada por p <strong>de</strong>s<strong>de</strong> el flujo f.<br />
SEEK_SET<br />
Principio <strong>de</strong> archivo.<br />
SEEK_CUR<br />
Posición actual puntero archivo.<br />
SEK_END<br />
Final <strong>de</strong> archivo.<br />
fseek(f1,OL,SEEK_SET); // ir al principio<br />
Funciones relacionadas: ftell, rewind, fopen.<br />
fread(buf, strlen(msg)+1, 1, flujo);<br />
Funciones relacionadas: fwrite, read.<br />
fsetpos<br />
int fsetpos(FILE *f, const fpos_t *p);<br />
#inclu<strong>de</strong> <br />
freopen<br />
#inclu<strong>de</strong> <br />
FILE *freopen(const char *f, const char *m, FILE *flujo);<br />
Cierra el archivo asociado con flujo y reasigna flujo al archivo especificado<br />
por f. Los modos (m) utilizados son los mismos <strong>de</strong> fopen.<br />
freopen(“salida.txt”, “w”, stdout);<br />
Funciones relacionadas: fclose, fopen.<br />
Establece la posición <strong>de</strong>l puntero <strong>de</strong>l archivo al lugar especificado por<br />
el objeto apuntado por p.<br />
fsetpos(fp, &posarch);<br />
Funciones relacionadas: getpos.<br />
ftell<br />
#inclu<strong>de</strong> <br />
long int ftell(FILE *f);<br />
Obtiene la posición actual (puntero) <strong>de</strong>l archivo asociado con el flujo f.<br />
fscanf<br />
#inclu<strong>de</strong> <br />
ftell(fichen);<br />
int fscanf(FILE *f, const char *formato [, dirección,...]);<br />
Funciones relacionadas: fgetpos, fssek, tell.
642 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
fwrite<br />
#inclu<strong>de</strong> <br />
size_t fwrite(const void *p, size_t l, size_t n, FILE *f);<br />
Escribe n elementos (registros) <strong>de</strong> longitud l <strong>de</strong>s<strong>de</strong> la memoria apuntada<br />
por p al archivo f. Devuelve el número <strong>de</strong> caracteres realmente escritos<br />
que, si la función tiene éxito, es igual al número indicado.<br />
num = fwrite(lista, sizeof(char),25,flujo);<br />
Devuelve el siguiente carácter <strong>de</strong> stdin. Si se alcanza el final <strong>de</strong> archivo,<br />
se <strong>de</strong>vuelve EOF.<br />
int c;<br />
while((c = getchar())!= ´\n´)<br />
printf(“%c”, c);<br />
Funciones relacionadas: fgetc, fgetchar, getch, getche, putc,<br />
putchar, ungetc.<br />
Funciones relacionadas: fread, fscanf, getc, fgetc.<br />
getche<br />
#inclu<strong>de</strong> <br />
getc<br />
#inclu<strong>de</strong> <br />
int getche(void);<br />
int getc(FILE *f);<br />
Devuelve el siguiente carácter <strong>de</strong> un flujo <strong>de</strong> entrada dado e incrementa<br />
la posición actual <strong>de</strong>l puntero <strong>de</strong>l archivo. Si se alcanza el final <strong>de</strong> archivo,<br />
se <strong>de</strong>vuelve EOF.<br />
whilec(c = getc(fx)!= EOF) {<br />
printf(“%c”, c);<br />
}<br />
Funciones relacionadas: getchar, fgetc, fputc, fputchr, putc,<br />
putchar, fopen.<br />
getch<br />
int getch(void)<br />
Lee un carácter <strong>de</strong>l teclado sin hacer eco en la pantalla.<br />
do {<br />
car = getch();<br />
char = toupper(car);<br />
} while(car != ´S´);<br />
#inclu<strong>de</strong> <br />
Funciones relacionadas: cgets, fgetc, getc, getchar, ungetch.<br />
Lee un carácter <strong>de</strong>l teclado haciendo eco <strong>de</strong>l carácter en la pantalla.<br />
resp= getche();<br />
Funciones relacionadas: cgets, getch, getchar, ungetch.<br />
gets<br />
char *gets(char *cad);<br />
#inclu<strong>de</strong> <br />
Lee una línea <strong>de</strong>s<strong>de</strong> el archivo <strong>de</strong> entrada estándar stdin, por omisión<br />
es el teclado y lo guarda en cad.<br />
gets(nombre);<br />
Funciones relacionadas: fgets, fputs, puts.<br />
getw<br />
int getw(FILE *f);<br />
Lee un entero (o una palabra <strong>de</strong> dos bytes) <strong>de</strong> un flujo f.<br />
#inclu<strong>de</strong> <br />
getchar<br />
int getchar(void);<br />
#inclu<strong>de</strong> <br />
suma = getw(fx) + suma;<br />
Funciones relacionadas: fread, putw.
BIBLIOTECA DE FUNCIONES ESTÁNDAR <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0 643<br />
printf<br />
#inclu<strong>de</strong> <br />
puts<br />
#inclu<strong>de</strong> <br />
int printf(const char *formato[,argumento,...]);<br />
Escribe ca<strong>de</strong>nas <strong>de</strong> caracteres y valores <strong>de</strong> variables, con formato, en el<br />
archivo <strong>de</strong> salida estándar stdout (por omisión, la pantalla).<br />
int puts(const char *cad);<br />
Escribe una ca<strong>de</strong>na en el archivo <strong>de</strong> salida estándar stdout.<br />
puts(“Desea continuar(s/n?”);<br />
Código<br />
Formato<br />
Funciones relacionadas: fgets, fputs, gets.<br />
%c Carácter.<br />
%d Entero <strong>de</strong>cimal.<br />
%e Real (double o float), notación científica.<br />
%f Coma flotante.<br />
%s Ca<strong>de</strong>na <strong>de</strong> caracteres.<br />
%x Hexa<strong>de</strong>cimal sin signo.<br />
printf(“producto %d y %d es %d\n”,x,y, x*y);<br />
Funciones relacionadas:<br />
vprintf, vsprintf.<br />
fprintf, scanf, sprintf, viprintf,<br />
putw<br />
int putw(int i, FILE *f);<br />
Escribe un entero en un flujo f.<br />
putw(100, fx);<br />
Funciones relacionadas: getw, printf.<br />
rewind<br />
void rewind(FILE *f);<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
putc, putchar<br />
#inclu<strong>de</strong> <br />
Reinicializa el puntero <strong>de</strong>l archivo al principio <strong>de</strong> un flujo.<br />
int putc(int c, FILE *f);<br />
int putchar(int c);<br />
Escribe un carácter en un flujo (putc) o en stdout (putchar).<br />
putc(´*´, <strong>de</strong>mo);<br />
Funciones relacionadas: fputc, fputchar, getc, getchar.<br />
rewind(fx);<br />
Funciones relacionadas: fseek.<br />
scanf<br />
#inclu<strong>de</strong> <br />
int scanf(const char *formato[,dirección,...]);<br />
Lee datos con formato <strong>de</strong>l flujo <strong>de</strong> entrada estándar.<br />
putch<br />
int putch(int c);<br />
Escribe un carácter en la pantalla.<br />
putch(´B´);<br />
Funciones relacionadas: putc, putchar.<br />
#inclu<strong>de</strong> <br />
Código<br />
Formato<br />
%c Carácter.<br />
%d Entero <strong>de</strong>cimal.<br />
%x Hexa<strong>de</strong>cimal.<br />
%i Entero <strong>de</strong>cimal.<br />
%f Número real.<br />
%o Octal.<br />
%p Puntero.<br />
%s Ca<strong>de</strong>na.
644 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
scanf(“%d %f %c %s”, &i, &fp, &c, s);<br />
Funciones relacionadas: fscanf, printf, sscanf, vfprintf,<br />
vprintf, vsprintf<br />
Esta función es idéntica a scanf, excepto que los datos son leídos <strong>de</strong>l<br />
array apuntado por b, en vez <strong>de</strong> stdin.<br />
sscanf(buffer, “%,s%s”,uno,dos,tres);<br />
setbuf<br />
#inclu<strong>de</strong> <br />
Funciones relacionadas: cscanf, fscanf, scanf, vscanf.<br />
void setbuf(FILE *f, char *buffer);<br />
Asigna un buffer a un flujo.<br />
tmpfile<br />
FILE *tmpfile(void);<br />
#inclu<strong>de</strong> <br />
setbuf(fx, buffer);<br />
Funciones relacionadas: setvbuf.<br />
setvbuf<br />
#inclu<strong>de</strong> <br />
Crea un archivo temporal y <strong>de</strong>vuelve un puntero a ese flujo.<br />
if((aux = tmpfile()) == NULL)...<br />
Funciones relacionadas: tmpnam.<br />
int setvbuf(FILE *f, char *b, int t, size_t l);<br />
tmpnam<br />
#inclu<strong>de</strong> <br />
Asigna el buffer b <strong>de</strong> tamaño l y el tipo t con el flujo (archivo) f. Los<br />
valores correctos <strong>de</strong> t son: _IOBF, _IONBF e _IOLBF.<br />
setvbuf(<strong>de</strong>mo, buffer, _IOFBF, 120);<br />
Funciones relacionadas: setbuf.<br />
sprintf<br />
int sprintf(char *b, const char *f[,arg,...]);<br />
#inclu<strong>de</strong> <br />
Escribe datos con formato en una ca<strong>de</strong>na. Se diferencia <strong>de</strong> printf en<br />
que la salida generada se sitúa en el array apuntado por b.<br />
sprintf(cad, “&s %d %c”, “uno”,5,´7´);<br />
Funciones relacionadas:<br />
vsprintf.<br />
sprintf, printf, vprintf, vfprintf,<br />
char *tmpnam(char *s);<br />
Genera un único nombre <strong>de</strong> archivo y lo guarda en el array apuntado por s.<br />
tmpnam(prueba);<br />
Funciones relacionadas: tmpfile.<br />
ungetc<br />
int ungetc(int c, FILE *f);<br />
#inclu<strong>de</strong> <br />
Sitúa un carácter, excepto la constante EOF, en el buffer asociado con un<br />
archivo abierto para entrada con buffer.<br />
ungetc(car, stdin);<br />
Funciones relacionadas: getc.<br />
sscanf<br />
#inclu<strong>de</strong> <br />
ungetch<br />
#inclu<strong>de</strong> <br />
int sscanf(const char *b, const char *f[,dirección,...]);<br />
int ungetch(int ch);
BIBLIOTECA DE FUNCIONES ESTÁNDAR <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0 645<br />
Empuja un carácter en la memoria intermedia <strong>de</strong>l teclado.<br />
char ch;<br />
ch = getch();<br />
ungetch(ch);<br />
vfprintf,<br />
vprintf,<br />
vsprintf<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
int vfprintf(FILE *f, const char *f, lista_va lista_arg);<br />
int vprintf(const char *f, lista_va lista_arg);<br />
int vsprintf(char *b, const char *f, lista_va lista_arg);<br />
Escribe salida con formato utilizando un puntero a una lista <strong>de</strong> argumentos.<br />
vprintf(formato, nota);<br />
Funciones relacionadas: fprintf, printf, sprintf, va_arg,<br />
va_end, va_strat.<br />
vsscanf<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
int vsscanf(const char *b, const char *f, lista_va<br />
lista_arg);<br />
Funciona igual que sscanf, excepto que en vsscanf es utilizado un<br />
puntero a una lista <strong>de</strong> variables en lugar <strong>de</strong> a las propias variables.<br />
vsscanf(buf_en, formato_p, arg_p);<br />
Funciones relacionadas: fscanf, sscanf, scanf, vfscanf, vscanf.<br />
Funciones <strong>de</strong> bajo nivel<br />
Las <strong>de</strong>claraciones <strong>de</strong> las <strong>funciones</strong> <strong>de</strong> bajo nivel se incluyen en los archivos<br />
<strong>de</strong> cabecera io.h, fcntl.h, sys|types.h y sys|sta.h. A diferencia <strong>de</strong><br />
las <strong>funciones</strong> stream, las <strong>funciones</strong> <strong>de</strong> bajo nivel no requieren el archivo <strong>de</strong><br />
inclusión stdio.h.<br />
vfscanf<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
int vfscanf(FILE *F, const char *f, lista_va lista_arg);<br />
Lee entrada con formato <strong>de</strong> un flujo, tal como scanf, excepto que vfscanf<br />
acepta un puntero a la lista <strong>de</strong> argumentos.<br />
vfscanf(<strong>de</strong>mo, formato, arg);<br />
Funciones relacionadas: fscanf, scanf, sscanf, vscanf, vsscanf.<br />
_close, close<br />
int _close(int h);<br />
int close(int h);<br />
#inclu<strong>de</strong> <br />
Cierra el archivo especificado en h. Estas <strong>funciones</strong> se utilizan con<br />
_open y open.<br />
close(f1);<br />
Funciones relacionadas: fclose, fopen, open.<br />
vscanf<br />
#inclu<strong>de</strong> <br />
int vscanf(const char *f, lista_va lista_arg);<br />
Lee una entrada con formato <strong>de</strong> un flujo; similar a scanf, excepto que<br />
vscanf acepta un puntero a la lista <strong>de</strong> argumentos.<br />
vscanf(formato, argumento);<br />
Funciones relacionadas: fscanf, scanf, sscanf, fsca.<br />
_creat<br />
creat<br />
int creat(const char *cam, int modo);<br />
int _creat(const char *cam, int atributo);<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
Crea un nuevo archivo o abre y trunca un archivo existente. _creat()<br />
actúa igual que creat(), excepto que utiliza un byte <strong>de</strong> atributo <strong>de</strong>l DOS.
646 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
Modo<br />
S_IWRITE<br />
S_IREAD<br />
S_IREAD|S_IWRITE<br />
Significado<br />
fh= creat(“datos”,S_IREAD|S_IWRITE);<br />
Permiso <strong>de</strong> escritura.<br />
Permiso <strong>de</strong> lectura.<br />
Permiso <strong>de</strong> lectura y escritura.<br />
Funciones relacionadas: chmod, close, open umask.<br />
creatnew<br />
int creatnew(const char *camino, int atributo);<br />
Crea un archivo nuevo con los atributos especificados.<br />
h = creatnew(“F.FIL”,0);<br />
Funciones relacionadas: _creat, fopen, open.<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
eof<br />
int eof(int d);<br />
#inclu<strong>de</strong> <br />
Comprueba si el archivo especificado en el <strong>de</strong>scriptor d es el final <strong>de</strong><br />
archivo (se <strong>de</strong>vuelve 1 si se alcanza el final <strong>de</strong>l archivo. 0 si no se alcanza<br />
el final <strong>de</strong>l archivo, –1 indica un error y errno toma valor EBADF: número<br />
<strong>de</strong> archivo incorrecto).<br />
while(!eof(fx))<br />
Funciones relacionadas: feof, ferror, perror.<br />
lseek<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
long lseek(int d, long <strong>de</strong>sp, int origen);<br />
La función lseek mueve el puntero asociado con el <strong>de</strong>scriptor d a una<br />
nueva posición que está emplazada <strong>de</strong>sp bytes <strong>de</strong> origen.<br />
pos = lseek(fh, OL, SEEK_CUR);<br />
creattemp<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
Funciones relacionadas: fseek, tell.<br />
int creattemp(char *camino, int atributo);<br />
Crea un único archivo temporal con byte <strong>de</strong> atributo en el directorio<br />
escrito por camino.<br />
if((h = creattemp(“nombre”,9))== -1<br />
Funciones relacionadas: tmpfile.<br />
open<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
int open(const char *f, int a[, unisgned m]);<br />
Abre el archivo especificado en f para lectura o escritura. El argumento<br />
a indica el tipo <strong>de</strong> operación permitida y m el tipo <strong>de</strong> permiso.<br />
dup, dup2<br />
#inclu<strong>de</strong> <br />
Indicador<br />
Lectura/escritura<br />
Significado<br />
int dup(int h);<br />
int dup2(int h1, int h2);<br />
Crea un segundo enlace a un archivo abierto (dup) o reasigna un enlace<br />
<strong>de</strong> archivo (dup2).<br />
viejostdout = dup(STDOUT);<br />
dup2(fptr, STDOUT);<br />
Funciones relacionadas: close, creat, open.<br />
O_RDONLY<br />
Abrir para lectura.<br />
O_WRONLY<br />
Abrir para escritura.<br />
O_RDWR<br />
Abrir para lectura y escritura.<br />
O_NDELAY<br />
Pone el puntero <strong>de</strong>l archivo al final <strong>de</strong>l archivo.<br />
O_APPEND<br />
Se crea el archivo y se fijan atributos <strong>de</strong>l archivo.<br />
O_TRUNC Trunca el archivo a 0.<br />
O_EXCL<br />
Se utiliza con O_CREAT.<br />
O_BINARY<br />
Abrir archivo en modo binario.<br />
O_TEXT<br />
Abrir archivo en modo texto.
BIBLIOTECA DE FUNCIONES ESTÁNDAR <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0 647<br />
open(“OPEN.OUT”, 0_WRONLY|O_CREAT, S_IREAD|IWRITE);<br />
if((h = open(“open.tst”, O_CREAT))==1)...<br />
Funciones relacionadas: access, chmod, close, creat, fopen.<br />
sopen<br />
int sopen(char *f, int a, int s[, int m]);<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
Abre un archivo f con acceso a en modo compartido en un entorno <strong>de</strong><br />
red y con el tipo s <strong>de</strong> compartición permitido en el archivo y modo m.<br />
Devuelve la posición actual <strong>de</strong>l puntero <strong>de</strong>l archivo especificado por d.<br />
posi = tell(<strong>de</strong>sf);<br />
Funciones relacionadas: ftell, lseek.<br />
write<br />
int write(int d, void *buffer, unsigned lon);<br />
#inclu<strong>de</strong> <br />
Escribe datos en un archivo (lon bytes en el archivo asociado con d<br />
<strong>de</strong>s<strong>de</strong> el buffer apuntado por buffer).<br />
write(fx, gran<strong>de</strong>, 60000);<br />
Indicador<br />
Lectura/escritura<br />
O_RDONLY<br />
O_WRONLY<br />
O_RDWR<br />
S_IWRITE<br />
S_IREAD<br />
S_IWRITE|S_IREAD<br />
Significado<br />
Abrir para lectura.<br />
Abrir para escritura.<br />
Abrir para lectura y escritura.<br />
Acceso <strong>de</strong> escritura.<br />
Acceso <strong>de</strong> lectura.<br />
Acceso <strong>de</strong> lectura y escritura.<br />
Funciones relacionadas: creat, open, read, sopen.<br />
Funciones <strong>de</strong> consola y puertos <strong>de</strong> E/S<br />
Las <strong>funciones</strong> <strong>de</strong> E/S sirven para interactuar con el teclado y la pantalla.<br />
Estas <strong>funciones</strong> se <strong>de</strong>claran en el archivo <strong>de</strong> cabecera conio.h.<br />
df = sopen(“C:||autoexec.bat”, O_RDONLY, SH_DENYRW, S_IREAD);<br />
Funciones relacionadas: close, fopen.<br />
read<br />
int read (int d, void * buffer, unsigned lon);<br />
#inclu<strong>de</strong> <br />
Lee lon bytes <strong>de</strong>l archivo asociado con d en el buffer apuntado por<br />
buffer.<br />
cgets<br />
char *cgets(char *ca<strong>de</strong>na);<br />
#inclu<strong>de</strong> <br />
Lee una ca<strong>de</strong>na <strong>de</strong> caracteres directamente <strong>de</strong> la consola, y almacena la<br />
ca<strong>de</strong>na y su longitud en la posición apuntada por ca<strong>de</strong>na.<br />
entrada = cgets(ca<strong>de</strong>na);<br />
Funciones relacionadas: cputs, getch, getche.<br />
read(fx, buffer, 100);<br />
cprintf<br />
#inclu<strong>de</strong> <br />
tell<br />
long tell(int d);<br />
#inclu<strong>de</strong> <br />
int cprintf(const char *formato[,arg,...]);<br />
Escribe salida con formato directamente en la consola. Observe que<br />
cprintf no traduce el carácter (\n) a una combinación (CR-LF), en su lugar,
648 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
\n se interpreta como avance <strong>de</strong> línea (LF) y \r se <strong>de</strong>be utilizar para indicar<br />
un retorno <strong>de</strong> carro (CR).<br />
cprintf(“Cubo <strong>de</strong> %2d es %rd\r\n”,i, i * i * i);<br />
Funciones relacionadas: printf.<br />
getpass<br />
char *getpass(const char *indicador);<br />
#inclu<strong>de</strong> <br />
Lee una palabra <strong>de</strong> paso por consola, que no se visualiza en pantalla<br />
(menos <strong>de</strong> ocho caracteres <strong>de</strong> longitud).<br />
cputs<br />
int cputs(const char *cad);<br />
#inclu<strong>de</strong> <br />
palabrapaso = getpass(“Introduzca clave”);<br />
Funciones relacionadas: getch<br />
Escribe una ca<strong>de</strong>na en la pantalla. No se envía ningún carácter <strong>de</strong> nueva<br />
línea <strong>de</strong>spués <strong>de</strong> la ca<strong>de</strong>na.<br />
cuts(“Está usted seguro(s/n)?”);<br />
inport, inportb<br />
int inport(int puerto);<br />
unsigned char inportb(int puerto);<br />
#inclu<strong>de</strong> <br />
Funciones relacionadas cprintf.<br />
cscanf<br />
int cscanf(char *formato [,dirección,...]);<br />
#inclu<strong>de</strong> <br />
Lee caracteres con formato directamente <strong>de</strong>s<strong>de</strong> la consola en la posición<br />
dada por dirección.<br />
Lee una palabra <strong>de</strong> 16 bits (inport) o un byte (inportb) <strong>de</strong> un puerto<br />
<strong>de</strong> E/S especificado por puerto.<br />
La función inport es útil para leer dos puertos adyacentes a la vez, e<br />
inportb para controlar dispositivos <strong>de</strong> entrada/salida.<br />
palabra = inport(PORT_8259_20);<br />
P21 = inportb(PORT_8259_21);<br />
Funciones relacionadas: outport, poutportb.<br />
cscanf(“%d%d%d, &dia, &mes, &hora);<br />
Funciones relacionadas: fscanf, scanf, sscanf.<br />
kbhit<br />
int kbhit(void);<br />
#inclu<strong>de</strong> <br />
Comprueba si se ha pulsado recientemente una tecla.<br />
get, getche<br />
int getch(void);<br />
int getche(void);<br />
#inclu<strong>de</strong> <br />
Lee un carácter <strong>de</strong> la consola sin eco (getch) o con eco (getche).<br />
printf(«Pulse cualquier tecla para salir»);<br />
getch();<br />
Funciones relacionadas: cgets, getchar, ungetch.<br />
// visualizar hasta que pulsa una tecla<br />
while(!kbhit())<br />
cputs(“Pulse una tecla”);<br />
Funciones relacionadas: getch, getche.<br />
outport, outportb<br />
void outport(int puerto, int palabra);<br />
void outportb(int puerto, unsigned char byte);<br />
#inclu<strong>de</strong>
BIBLIOTECA DE FUNCIONES ESTÁNDAR <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0 649<br />
Escribe una palabra <strong>de</strong> 16 bits (outport) un byte (outportb) en un<br />
puerto <strong>de</strong> E/S.<br />
outport(23,0);<br />
outport(´A´, 0)<br />
// 23 fuera <strong>de</strong>l puerto<br />
// A fuera <strong>de</strong> puerto<br />
Funciones relacionadas: inp, inport, inportb, inpw.<br />
putch<br />
int putch(int c);<br />
Escribe un carácter en la consola (sin acción <strong>de</strong>l buffer).<br />
putch(car); putch(´\n´); putch(´x´);<br />
Funciones relacionadas: getch, getche.<br />
ungetch<br />
int ungetch(int c);<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
Sitúa un carácter en el buffer <strong>de</strong>l teclado <strong>de</strong> modo que es el siguiente<br />
carácter leído en la consola.<br />
if(c =!EOF) ungetch(c);<br />
ungetch(car);<br />
Funciones relacionadas: getch, getche, ungetc.<br />
F.11.<br />
FUNCIONES DE GESTIÓN DE ARCHIVOS<br />
Verifica si existe un archivo y, en caso afirmativo, los permisos <strong>de</strong> acceso<br />
al archivo.<br />
Modo<br />
Significado<br />
00 Se verifica existencia <strong>de</strong>l archivo.<br />
01 Ejecutar.<br />
02 Verifica permiso <strong>de</strong> escritura.<br />
04 Verifica permiso <strong>de</strong> lectura.<br />
06 Verifica permiso <strong>de</strong> lectura y escritura.<br />
return(access(nombre, 4)==-1)<br />
Funciones relacionadas: chmod, fstat, stat.<br />
chmod<br />
int chmod(const char *camino, int pmodo);<br />
Cambia los permisos <strong>de</strong> lectura/escritura <strong>de</strong> un archivo.<br />
r = chmod(“prueba.tst”, S_IREAD);<br />
Funciones relacionadas: access, fstat, stat.<br />
pmodo<br />
S_IWRITE<br />
S_IREAD<br />
S_IREAD|S_IWRITE<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
Permiso <strong>de</strong> acceso<br />
Escritura.<br />
Lectura.<br />
Lectura/Escritura.<br />
El sistema <strong>de</strong> archivos es un componente clave <strong>de</strong>l/<strong>de</strong> la PC. Todas las aplicaciones<br />
y datos resi<strong>de</strong>n en archivos. Las <strong>funciones</strong> <strong>de</strong> gestión <strong>de</strong> archivos<br />
permiten establecer y verificar permisos <strong>de</strong> acceso a archivos. La mayoría<br />
<strong>de</strong> las <strong>funciones</strong> están en el archivo <strong>de</strong> cabecera io.h, y las restantes en<br />
sys|stat.h, dir.h y stdio.h.<br />
chsize<br />
int chsize(int manejador, long longitud);<br />
Cambia el tamaño <strong>de</strong>l archivo.<br />
#inclu<strong>de</strong> <br />
access<br />
int access(const char *nomarch, int modo);<br />
#inclu<strong>de</strong> <br />
chsize(fh, 5);<br />
Funciones relacionadas: access, chmod, fstat, stat.
650 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
filelength<br />
long filelenght(int manejador);<br />
Obtiene la longitud <strong>de</strong> un archivo en bytes.<br />
filelength(fh);<br />
Funciones relacionadas: fileno, filestat, stat.<br />
fnmerge<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
void fnmerge(char *camino, const char *unidad,<br />
const char *dir, const char *nombref, const char *ext);<br />
Crea un nombre <strong>de</strong> camino completo (letra, unidad, camino directorio,<br />
nombre <strong>de</strong> archivo y extensión <strong>de</strong>l archivo). En Microsoft, la función equivalente<br />
es _makepath.<br />
fnmerge(camino,”C:”,\\aux,”resultado”,”.dat”);<br />
// nombre <strong>de</strong> camino”C:\aux\resultado.dat”<br />
Funciones relacionadas: fnsplit.<br />
fnsplit<br />
int fnsplit(const char *camino, char *unidad,<br />
char *dir, char *fnombre, char *ext);<br />
#inclu<strong>de</strong> <br />
Devuelve información sobre el archivo especificado en la estructura <strong>de</strong><br />
tipo stat apuntada por buffer. La estructura stat es:<br />
struct stat {<br />
short st_<strong>de</strong>v;<br />
short st_ino;<br />
short st_mo<strong>de</strong><br />
short st_nlink;<br />
int st_uid;<br />
int st_gid;<br />
int st_r<strong>de</strong>v;<br />
long st_size;<br />
long st_atime;<br />
long st_mtime;<br />
long st_ctime;<br />
};<br />
fstat(fich, &info);<br />
// unidad o dispositivo<br />
// número inodo (UNIX)<br />
// modo archivo<br />
// número enlaces (DOS,1)<br />
// id <strong>de</strong> usuario (UNIX)<br />
// id <strong>de</strong> grupo (sólo UNIX)<br />
// dispositivo UNIX<br />
// tamaño archivo en bytes<br />
// hora último acceso<br />
// hora última (UNIX)<br />
// hora creación<br />
Funciones relacionadas: access, chmod, stat.<br />
isatty<br />
int isatty(int h);<br />
#inclu<strong>de</strong> <br />
Determina si es un dispositivo orientado a carácter (terminal, consola,<br />
impresora o puerto serie).<br />
if(isatty(fileno(stdout)))<br />
puts(“es consola”);<br />
Separa un nombre <strong>de</strong> camino completo en sus componentes: letra, unidad,<br />
camino, nombre y extensión <strong>de</strong>l archivo.<br />
f = fnsplit(c, unidad, dir, arch, ext);<br />
lock<br />
int lock(int h, long d, long n);<br />
#inclu<strong>de</strong> <br />
Funciones relacionadas: fnmerge.<br />
Bloquea un número <strong>de</strong> bytes n <strong>de</strong>l archivo h (manejador) con <strong>de</strong>splazamiento<br />
se utiliza para compartición <strong>de</strong> archivos (or<strong>de</strong>n SHARE <strong>de</strong> MS-<br />
DOS). En Visual <strong>C++</strong>, la función equivalente es locking.<br />
fstat<br />
#inclu<strong>de</strong> <br />
res lock(h, 0L,256);<br />
bloque <strong>de</strong> 256 bytes<br />
int fstat(int h, struct stat *buffer);<br />
Funciones relacionadas: sopen, unlock.
mktemp<br />
char * mktemp(char *plantilla);<br />
#inclu<strong>de</strong> <br />
BIBLIOTECA DE FUNCIONES ESTÁNDAR <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0 651<br />
modo 0_BINARY(binario) 0_TEXT(texto)<br />
setmo<strong>de</strong>(fileno(stdin), 0_BINARY);<br />
// modo binario<br />
Crea un único nombre <strong>de</strong> archivo modificando una plantilla dada como<br />
argumento, plantilla toma la forma basexxxxxx, don<strong>de</strong> bas es el nombre<br />
que se proporciona y x los caracteres a modificar.<br />
char mo<strong>de</strong>lo = “tcbxxxxxx”;<br />
mktemp(mo<strong>de</strong>lo);<br />
Funciones relacionadas: tmpfile, tmpnam.<br />
Funciones relacionadas: fopen, open.<br />
stat<br />
#inclu<strong>de</strong> <br />
int stat(char *f, struct stat *buffer);<br />
Obtiene información sobre el estado <strong>de</strong> un archivo existente f.<br />
resultado = stat(“stat.c”,&buf);<br />
remove<br />
#inclu<strong>de</strong> <br />
Funciones relacionadas: access, chmod, fstat.<br />
int remove(const char *camino);<br />
Borra el archivo especificado en camino.<br />
remove(“C:\\ux\\<strong>de</strong>mo”); // borra <strong>de</strong>mo<br />
Funciones relacionadas: unlink.<br />
rename<br />
#inclu<strong>de</strong> <br />
int rename(const char *vn, const char *nn);<br />
Renombre el archivo vn a nn.<br />
umask<br />
unsigned umask(unsigned Pmodo);<br />
#inclu<strong>de</strong> <br />
Establece la máscara <strong>de</strong> permisos <strong>de</strong> lectura/escritura usados por open<br />
y create.<br />
Pmodo S_IREAD (sólo lectura)<br />
S_IWRITE (sólo escritura)<br />
S_IREAD|S_IWRITE (lectura/escritura)<br />
viejamascara = umask(S_IWRITE);<br />
Funciones relacionadas: chmod, creat, mkdir, open, sopen.<br />
int resultado;<br />
resultado = rename(viejo, nuevo);<br />
Funciones relacionadas: creat, fopen, open.<br />
unlink<br />
int unlink(const char *camino);<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
setmo<strong>de</strong><br />
int setmo<strong>de</strong>(int h, int modo);<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
Borra un archivo especificado en camino, que no sea <strong>de</strong> sólo lectura.<br />
result = unlink (“<strong>de</strong>mo.jnk”);<br />
if (result==0)<br />
printf (“unlink tuvo éxito”);<br />
Permite cambiar el modo <strong>de</strong>l archivo abierto entre texto y binario.<br />
Funciones relacionadas: remove.
652 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
unlock<br />
#inclu<strong>de</strong> <br />
int unlock(int h, long o, long l);<br />
Desbloquea una sección <strong>de</strong>l archivo h que ha sido bloqueada con lock.<br />
unlock(m,OL,256); // <strong>de</strong>sbloquea 256 bytes<br />
Funciones relacionadas: lock, sopen.<br />
Las <strong>funciones</strong> complejas son propias <strong>de</strong> Borland <strong>C++</strong> y no son exportables.<br />
Clase bcd<br />
La clase bcd permite manipular números almacenados en notación <strong>de</strong>cimal<br />
codificado a binario (BCD) y proporciona hasta 17 dígitos <strong>de</strong>cimales <strong>de</strong><br />
precisión, y un rango <strong>de</strong> 1 × 10 -125 a 1 × 10 125 .<br />
F.12.<br />
FUNCIONES MATEMÁTICAS<br />
El C original <strong>de</strong> K&R fue diseñado, inicialmente, como un lenguaje <strong>de</strong> programación<br />
<strong>de</strong> sistemas, su uso ha sido muy escaso en el campo <strong>de</strong>l cálculo<br />
científico. Sin embargo, <strong>de</strong>s<strong>de</strong> la normalización <strong>de</strong> <strong>ANSI</strong> C y su extensa<br />
biblioteca matemática, C se ha convertido en un fuerte rival <strong>de</strong>l lenguaje<br />
científico por excelencia, FORTRAN. C soporta operaciones <strong>de</strong> coma flotante<br />
e incluye también un rico conjunto <strong>de</strong> <strong>funciones</strong> matemáticas. Borland<br />
<strong>C++</strong> ha ampliado las propieda<strong>de</strong>s <strong>de</strong> <strong>ANSI</strong> C estándar.<br />
Los archivos <strong>de</strong> cabecera que contienen <strong>funciones</strong> matemáticas son:<br />
bcd.h, complex.h, float.h, math.h, stdlib.h. Las <strong>funciones</strong> <strong>de</strong> Borland<br />
<strong>C++</strong> no incluidas en <strong>ANSI</strong> C son: cabs, _clear87, _control87,<br />
_fpreset, hypot, _lrotl, _rotr, _matherr, matherrmax, min,<br />
poly, pow10, random, randomize, _rotl, _rotr, _status87.<br />
A<strong>de</strong>más <strong>de</strong> estas <strong>funciones</strong>, Borland <strong>C++</strong> soporta dos clases específicas<br />
importantes: complex y bcd, se encuentran en los archivos complex.h y<br />
bcd.h, respectivamente.<br />
Clase complex<br />
Borland <strong>C++</strong> incluye una estructura complex en el archivo <strong>de</strong> cabecera<br />
math.h, cuyos miembros son la parte real e imaginaria <strong>de</strong> un número complejo<br />
z y que se <strong>de</strong>fine así:<br />
struct complex<br />
{<br />
double x;<br />
double y;<br />
}<br />
// parte real <strong>de</strong>l número complejo<br />
// parte imaginaria <strong>de</strong>l complejo<br />
abs versión real<br />
versión compleja<br />
int abs (int x);<br />
double abs(complex x);<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
Proporciona el valor absoluto <strong>de</strong> un entero o <strong>de</strong> un número complejo:<br />
abs(-50) <strong>de</strong>vuelve 50. Para utilizar números complejos se requiere el<br />
archivo <strong>de</strong> cabecera complex.h.<br />
x = abs(-7) // x es 7<br />
Funciones relacionadas: cabs, fabs, labs.<br />
acos<br />
double acos(double x);<br />
complex acos(complex x);<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
La función acos() <strong>de</strong>vuelve el arco coseno <strong>de</strong> x, cuyo valor <strong>de</strong>be estar<br />
en el rango –1 a 1. El resultado es un valor (ángulo) entre 0 y radianes.<br />
angulo = acos(0.5); // el ángulo <strong>de</strong>vuelto es /3<br />
Funciones relacionadas: cos, matherr.<br />
Se pue<strong>de</strong> <strong>de</strong>clarar e inicializar un número complejo (x + yi) <strong>de</strong> esta<br />
forma:<br />
arg<br />
#inclu<strong>de</strong> <br />
struct complex z = {1.5,1.5}<br />
// z = 1.5 + i1.5;<br />
double arg(complex x);
BIBLIOTECA DE FUNCIONES ESTÁNDAR <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0 653<br />
La función arg() <strong>de</strong>vuelve el ángulo, en radianes, <strong>de</strong> un número en el<br />
plano complejo.<br />
complex z;<br />
double angulo;<br />
z = complex(1.5, 4.5);<br />
angulo = arg(z);<br />
Calcula el arco tangente <strong>de</strong> y/x. El resultado es un ángulo <strong>de</strong> valor<br />
comprendido entre – y radianes.<br />
angulo = atan2(y, x);<br />
Funciones relacionadas: atan, matherr, tan.<br />
Funciones relacionadas: complex, norm, polar.<br />
cabs<br />
#inclu<strong>de</strong> <br />
asin versión real<br />
versión compleja<br />
double asin(double x);<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
Calcula el arco seno <strong>de</strong>l argumento x; el valor <strong>de</strong> x <strong>de</strong>be estar comprendido<br />
entre –1 y 1. La función asin() <strong>de</strong>vuelve un valor entre –/2 y ,<br />
el valor <strong>de</strong> x <strong>de</strong>be ser en radianes.<br />
Z = asin(0.7543);<br />
Funciones relacionadas: matherr, sin.<br />
double babs(struct complex z);<br />
Calcula el valor absoluto <strong>de</strong> un número complejo almacenado en una<br />
estructura <strong>de</strong> tipo complex.<br />
struct complex z;<br />
double complejo;<br />
z.y = 3.5<br />
z.y = 2.4<br />
complejo = cabs(z);<br />
printf(“valor absoluto %lf\n”, complejo);<br />
Funciones relacionadas: fabs, hypot, matherr, sqrt.<br />
atan versión real<br />
versión compleja<br />
double atan(double x);<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
ceil<br />
#inclu<strong>de</strong> <br />
double ceil (double x);<br />
Calcula (redon<strong>de</strong>a) el número entero mayor que o igual a x.<br />
Calcula el arco tangente <strong>de</strong> x. El rango x es –1 a 1. La función atan()<br />
<strong>de</strong>vuelve un valor en el rango <strong>de</strong> –/2 a /2.<br />
#inclu<strong>de</strong> <br />
complex atan(complex x);<br />
angulo = atan(1.0);<br />
Funciones relacionadas: atan2.<br />
// ángulo es “Pi/4” (45 grados)<br />
redon<strong>de</strong>o = ceil(5.1) // redon<strong>de</strong>o es 6<br />
Funciones relacionadas: floor.<br />
_clear87<br />
#inclu<strong>de</strong> <br />
unsigned int _clear87(void);<br />
Borra (limpia) la palabra <strong>de</strong>l estado <strong>de</strong> coma flotante.<br />
atan2<br />
double atan2 (double y, double x);<br />
#inclu<strong>de</strong> <br />
estado = _clear87();<br />
Funciones relacionadas: _control87, _status87.
654 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
_control87<br />
#inclu<strong>de</strong> <br />
unsigned int _control87(unsigned int nuevo, unsigned int<br />
mascara);<br />
Obtiene y establece la palabra <strong>de</strong> control <strong>de</strong> coma flotante. Cuando se<br />
utiliza un coprocesador matemático 8087, _control87 establece su palabra<br />
<strong>de</strong> control.<br />
estado = control87(PC24,MCW_IC);<br />
// precisión 24 bits<br />
Funciones relacionadas: _clear87, _status87.<br />
La función div() calcula el cociente entero y el resto <strong>de</strong> x por y. La<br />
función <strong>de</strong>vuelve una estructura div_t <strong>de</strong>finida en stdlib.h como<br />
type<strong>de</strong>f struct<br />
{<br />
int quot;<br />
int rem;<br />
} div_t;<br />
// cociente<br />
// resto<br />
div_t resultado;<br />
resultado = div(35, 8);<br />
// resultado.cociente = 4, resultado.resto = 3<br />
cos<br />
#inclu<strong>de</strong> <br />
exp<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
double cos(double x);<br />
complex cos(complex x);<br />
double exp(double x);<br />
complex exp(complex x);<br />
Calcula el coseno <strong>de</strong>l argumento x. El argumento x se especifica en<br />
radianes y <strong>de</strong>vuelve un valor en el rango <strong>de</strong> –1 a 1.<br />
coseno_x = cos(1.6543);<br />
Funciones relacionadas: acos, sin.<br />
Calcula el exponencial <strong>de</strong> x:e x ; don<strong>de</strong> e es la base <strong>de</strong>l logaritmo natural<br />
(e = 2.7182818).<br />
x = 100.00;<br />
y = exp(x);<br />
printf(“El exponencial <strong>de</strong> x = %f.\n”,y);<br />
cosh<br />
#inclu<strong>de</strong> <br />
Funciones relacionadas: log, pow.<br />
double cosh(double x);<br />
complex cosh(complex x);<br />
Calcula el coseno hiperbólico <strong>de</strong> la variable x. Si el argumento pasado<br />
a cosh() es <strong>de</strong>masiado gran<strong>de</strong>, se produce un error <strong>de</strong> rango.<br />
fabs, fabsl<br />
double fabs(double x);<br />
long double fabs(long double x);<br />
#inclu<strong>de</strong> <br />
x = 1.00<br />
printf(“x = %f.\n\n”,x);<br />
y = cosh(x);<br />
printf(“coseno hiperbólico x = %f.\n\n”, y);<br />
Funciones relacionadas: sinh.<br />
Calcula el valor absoluto <strong>de</strong> un número en coma flotante x.<br />
y = fabs(-7.25); // y vale 7.25<br />
Funciones relacionadas: cabs.<br />
div<br />
#inclu<strong>de</strong> <br />
floor<br />
#inclu<strong>de</strong> <br />
div_t div(int x, int y);<br />
double floor(double x);
BIBLIOTECA DE FUNCIONES ESTÁNDAR <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0 655<br />
Redon<strong>de</strong>a por <strong>de</strong>fecto el valor <strong>de</strong> x.<br />
x = floor(6.25); // x vale 6<br />
Funciones relacionadas: ceil.<br />
double x, y;<br />
int n;<br />
x = 17.5;<br />
y = frexp(x, &n);<br />
printf(“frexp(%f, &n) = %f, n = %d\n”,x,y,n);<br />
Funciones relacionadas: exp, l<strong>de</strong>xp, modf.<br />
fmod<br />
#inclu<strong>de</strong> <br />
hypot<br />
#inclu<strong>de</strong> <br />
double fmod(double x, double y);<br />
Calcula el resto <strong>de</strong> la división real x por y.<br />
resto = (fmod(5.0, 2.0); // resto igual a 1.0<br />
Funciones relacionadas: floor.<br />
_fpreset<br />
void _fpreset(void);<br />
#inclu<strong>de</strong> <br />
Reinicializa el paquete matemático <strong>de</strong> coma flotante. Debe utilizarse<br />
<strong>de</strong>spués <strong>de</strong> las llamadas a las <strong>funciones</strong> system(), exec(), span() sobre<br />
máquinas con coprocesadores matemáticos.<br />
_fpreset(); // inicializa paquete <strong>de</strong> coma flotante *t<br />
Funciones relacionadas: _control87, signal.<br />
double hypot(double x, double y);<br />
Calcula la hipotenusa <strong>de</strong> un triángulo rectángulo cuyos lados son x e y.<br />
Una llamada a hypot equivale a lo siguiente:<br />
sqrt(x * x, y * y);<br />
double x = 3.0; y = 4.0;<br />
printf(“%lf”, hypot(x, y));<br />
imag<br />
double imag(complex x);<br />
#inclu<strong>de</strong> <br />
Devuelve la parte imaginaria <strong>de</strong> un número complejo x. Esta función no<br />
es transportable.<br />
double x = 3.4, y = 4.5;<br />
complex = complex(x, y);<br />
cout
656 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
l<strong>de</strong>sp, l<strong>de</strong>spl<br />
double l<strong>de</strong>sp(double x, int exp);<br />
long double l<strong>de</strong>xpl(long double x, int exp);<br />
Calcula y <strong>de</strong>vuelve el valor real <strong>de</strong> x*e exp .<br />
double x = 4.0,y;<br />
int p = 5;<br />
y = l<strong>de</strong>xp(x, p);<br />
#inclu<strong>de</strong> <br />
st<strong>de</strong>rr, la variable global errno toma el valor EDOM y <strong>de</strong>vuelve el valor<br />
HUGE_VAL. Si x es 0, la función imprime un mensaje <strong>de</strong> error SING en<br />
st<strong>de</strong>rr, <strong>de</strong>vuelve el valor HUGE_VAL y fija errno a ERANGE.<br />
hdouble x, y;<br />
x = 10;<br />
y = log(x);<br />
y = log10(x);<br />
Funciones relacionadas: exp, matherr pow.<br />
Funciones relacionadas: frexp, modf.<br />
_lrotl<br />
#inclu<strong>de</strong> <br />
ldiv<br />
ldiv_t ldiv(long int x, long int y);<br />
#inxlu<strong>de</strong> <br />
Calcula el cociente y el resto <strong>de</strong> la división x/y. La función ldiv<br />
<strong>de</strong>vuelve una estructura <strong>de</strong> tipo ldiv_t que compren<strong>de</strong> el cociente y el<br />
resto.<br />
type<strong>de</strong>f struct<br />
{<br />
long quot;<br />
long rem;<br />
} ldiv_t;<br />
long x = 5258625, y = 341654;<br />
ldiv_t resultado;<br />
resultado = ldiv(x, y);<br />
printf(“el cociente y el resto es %ld, %ld,\n”, resultado.quot,<br />
resultado.rem);<br />
Funciones relacionadas: div.<br />
unsigned long _lrotl(unsigned long x, int c);<br />
Se utiliza _lrotl para rotar a la izquierda los bits <strong>de</strong> una variable entera<br />
larga sin signo x. La rotación <strong>de</strong> un bit a la izquierda, una posición, significa<br />
que el bit más a la izquierda sale fuera y se inserta en su posición el<br />
siguiente bit <strong>de</strong> mayor peso, y los restantes bits se <strong>de</strong>splazan una posición a<br />
la izquierda.<br />
unsigned long x = 0x0fac45491;<br />
printf(“x <strong>de</strong>splazado 4 veces es”, _lrotl (x, 4);<br />
Funciones relacionadas: _lrotr, _rotl, _rotv.<br />
_lrotr<br />
unsigned long _lrotr(unsigned long x, int c);<br />
#inclu<strong>de</strong> <br />
Rota a la <strong>de</strong>recha los bits <strong>de</strong> x. Rotación a <strong>de</strong>recha <strong>de</strong> un bit significa<br />
salir fuera el bit <strong>de</strong> menor peso y los restantes se <strong>de</strong>splazan una posición a<br />
la <strong>de</strong>recha.<br />
val_r = _lrotr(x, 4);<br />
log, log10<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
Funciones relacionadas: _lrotl, _rotl, _rotr.<br />
double log(double x);<br />
double log10(double x);<br />
Calcula el logaritmo natural (neperiano) y el logaritmo en base 10 <strong>de</strong> x.<br />
Si x es negativo, ambas <strong>funciones</strong> <strong>de</strong>vuelven un error <strong>de</strong> dominio DOMAIN en<br />
matherr<br />
_matherrl<br />
int matherr(struct exception *e);<br />
int _matherrl(struct _exception1 *e)<br />
#inclu<strong>de</strong>
BIBLIOTECA DE FUNCIONES ESTÁNDAR <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0 657<br />
Esta función manipula errores matemáticos. Las <strong>funciones</strong> matemáticas<br />
llaman a la rutina a<strong>de</strong>cuada matherr cuando se <strong>de</strong>tecta un error. Se pue<strong>de</strong><br />
<strong>de</strong>sarrollar su propia versión <strong>de</strong> matherr para personalizar su tratamiento<br />
<strong>de</strong> errores. Para profundizar en esta función, consultar su referencia en<br />
Library Reference <strong>de</strong> Borland <strong>C++</strong> (págs. 352-353).<br />
Funciones relacionadas: Las <strong>funciones</strong> matemáticas.<br />
max<br />
#inclu<strong>de</strong> <br />
(tipo) max(a, b);<br />
Devuelve el mayor <strong>de</strong> dos valores. Ambos argumentos y la <strong>de</strong>claración<br />
<strong>de</strong> la función <strong>de</strong>ben ser <strong>de</strong>l mismo tipo.<br />
double dbl1, dbl2, dblmax;<br />
dblmax = max(dbl1, dbl2);<br />
Funciones relacionadas: min.<br />
min<br />
#inclu<strong>de</strong> <br />
(tipo) min(a, b);<br />
Devuelve el menor <strong>de</strong> dos valores. Ambos argumentos y la <strong>de</strong>claración<br />
<strong>de</strong> la función <strong>de</strong>ben ser <strong>de</strong>l mismo tipo.<br />
int i1, i2, minent;<br />
minent = min(i1, i2);<br />
polar<br />
complex polar(double modulo, double angulo);<br />
#inclu<strong>de</strong> <br />
Devuelve un número complejo con una magnitud (módulo) y ángulo<br />
dado.<br />
complex < = complex(x, y);<br />
polar(mag, ang)es lo mismo que complex(mag*cos(ang), mag<br />
*sin(ang);<br />
Funciones relacionadas: Sólo existe en C+.<br />
poly<br />
double poly(double x, int n, double c[]);<br />
#inclu<strong>de</strong> <br />
Se utiliza poly para evaluar un polinomio en x, <strong>de</strong> grado n y cuyos coeficientes<br />
son los correspondientes al array c. La expresión utilizada para<br />
evaluar el polinomio es:<br />
c[n]x n +c[n-1] n-1 +...+c[2](x 2 +c[1](x+c[0]<br />
// polinomio: 3x**2 + 2x + 1//<br />
double c[] = {-10.0,2,c);<br />
Funciones relacionadas: pow.<br />
Funciones relacionadas: max.<br />
rand<br />
#inclu<strong>de</strong> <br />
modf, modfl<br />
#inclu<strong>de</strong> <br />
int rand(void);<br />
double modf(double x, double *partent);<br />
long double modfl(long double x, long double *partent);<br />
La función modf divi<strong>de</strong> un número <strong>de</strong> coma flotante en dos partes, entera<br />
y <strong>de</strong>cimal. La parte entera <strong>de</strong> x se almacena en la posición a cuya dirección<br />
apunta partent, y la parte <strong>de</strong>cimal es <strong>de</strong>vuelta por la función.<br />
par<strong>de</strong>cimal = modf(36.95, &parte_entera(;<br />
// parte entera 36, parte <strong>de</strong>cimal .95<br />
Funciones relacionadas: frexp,l<strong>de</strong>xp.<br />
Genera un número pseudoaleatorio en el rango <strong>de</strong> 0 a RAND_MAX; esta<br />
constante simbólica está <strong>de</strong>finida en y su valor es 2 15 -1. Para inicializar<br />
el generador <strong>de</strong> números pseudoaleatorios se <strong>de</strong>be utilizar randomize.<br />
Para obtener un número en el rango <strong>de</strong> 0 a (n-1) hay que utilizar random.<br />
// visualizar 10 números aleatorios //<br />
for(i = 0; 1 < 10; i++)<br />
printf(“%6d\”, rand());<br />
Funciones relacionadas: random, randomize, srand.
658 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
random<br />
#inclu<strong>de</strong> <br />
Rota el valor <strong>de</strong> x,c bits a la izquierda.<br />
int random(int x);<br />
Genera un número pseudoaleatorio en el rango <strong>de</strong> 0 a x-1.<br />
// obtener un número aleatorio entre 0 y 20<br />
numa1 = random(21);<br />
Funciones relacionadas: rand, randomize.<br />
mo<strong>de</strong>lo_nuevo = _rotl(0x1234,8);<br />
// resultado es 3412h<br />
Funciones relacionadas: _lrotl, _rotr, _rotr.<br />
_rotr<br />
unsigned _rotr(unsigned x, int c);<br />
#inclu<strong>de</strong> <br />
randomize<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
Se utiliza _rotr para rotar a la <strong>de</strong>recha el valor <strong>de</strong> x,c bits.<br />
_rotr(val, 4);<br />
void randomize(void);<br />
Inicializa (genera una semilla) el generador <strong>de</strong> números pseudoaleatorios<br />
con una semilla aleatoria que es función <strong>de</strong> la hora actual. Esta función<br />
impi<strong>de</strong> que se repitan las mismas secuencias <strong>de</strong> números aleatorios en diferentes<br />
ejecuciones.<br />
randomize();<br />
Funciones relacionadas: rand, random, srand.<br />
real<br />
double real(complex x);<br />
double real(bcd x);<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
Devuelve la parte real <strong>de</strong> un número complejo x o convierte un número<br />
BCD a float, double o long double.<br />
complex z = complex(x, y)<br />
cout
BIBLIOTECA DE FUNCIONES ESTÁNDAR <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0 659<br />
sqrt<br />
double sqrt(double x);<br />
complex sqrt(complex x);<br />
Calcula la raíz cuadrada <strong>de</strong> un número x no negativo.<br />
printf(“%lf”,sqrt(25.0); // se visualiza 5<br />
Funciones relacionadas: exp, log, pow.<br />
srand<br />
void srand(unsigned x);<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
srand inicializa el generador <strong>de</strong> números aleatorios con la semilla x. Si<br />
x es 1, el generador se reinicializa; cualquier otro valor <strong>de</strong> x fija el generador<br />
a un punto inicial aleatorio.<br />
srand(semilla);<br />
Funciones relacionadas: rand, randomize.<br />
_status87<br />
#inclu<strong>de</strong> <br />
tanh<br />
double tanh(double x);<br />
complex tanh(complex x);<br />
Calcula la tangente hiperbólica <strong>de</strong> x.<br />
a = tanh(x);<br />
Funciones relacionadas: cosh, tanh.<br />
F.13.<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
FUNCIONES DE MANIPULACIÓN DE BLOQUES<br />
DE MEMORIA (BUFFERS)<br />
Las rutinas <strong>de</strong> manipulación <strong>de</strong> buffers son una forma general <strong>de</strong> las rutinas<br />
<strong>de</strong> manipulación <strong>de</strong> ca<strong>de</strong>nas que operan sobre éstas en C. Son útiles para trabajar<br />
con áreas <strong>de</strong> memoria sobre la base <strong>de</strong> carácter a carácter. Un buffer es<br />
un array <strong>de</strong> caracteres similar a una ca<strong>de</strong>na <strong>de</strong> caracteres. Sin embargo, al<br />
contrario que las ca<strong>de</strong>nas, los buffers no terminan normalmente con un<br />
carácter nulo (´\0´). Por consiguiente, las rutinas <strong>de</strong> manipulación <strong>de</strong> buffers<br />
siempre toman un argumento longitud o cuenta.<br />
Las rutinas <strong>de</strong> manipulación requieren que el archivo <strong>de</strong> cabecera<br />
se incluya en su programa.<br />
unsigned int _status87(void);<br />
Obtiene el contenido <strong>de</strong> la palabra <strong>de</strong> estado <strong>de</strong> coma flotante.<br />
estado = _status87();<br />
Funciones relacionadas: _clear87, _control87.<br />
tan<br />
double tan(double x);<br />
complex tan(complex x);<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
memccpy<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
void *memccpy(void *<strong>de</strong>st, const void *s, int c, size_t n);<br />
Copia n bytes <strong>de</strong>s<strong>de</strong> s a <strong>de</strong>st hasta que n bytes han sido copiados o c<br />
se copia a <strong>de</strong>st.<br />
res = memccpy(buf_<strong>de</strong>st, bufen, ´c´, 81);<br />
Funciones relacionadas: memcpy, memmove, movedata, movmem.<br />
Calcula la tangente <strong>de</strong> x (x, se supone en radianes).<br />
y = tan(x)<br />
memchr<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
Funciones relacionadas: atan.<br />
void *memchr(const void *buf, int c, size_t n);
660 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
Busca un carácter específico c en un buffer (buf) examinando los n primeros<br />
caracteres.<br />
result = memchr(direc, ´I´, 40);<br />
Funciones relacionadas: memcmp, memicmp.<br />
memmove<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
void *memmove(void *<strong>de</strong>st, const void *f, size_t n);<br />
Mueve n bytes <strong>de</strong> un buffer (f) a otro (<strong>de</strong>st).<br />
memcmp<br />
#inclu<strong>de</strong> <br />
Funciones relacionadas: memccpy, memcpy, movedata.<br />
int memcmp(const void *b1, const void *b2, size_t n);<br />
Compara n bytes <strong>de</strong> un buffer (b1) con los <strong>de</strong> otro buffer (b2). Devuelve<br />
un valor:<br />
< 0 si b1 < b2<br />
= 0 si b1 = b2<br />
> 0 si b1 > b2<br />
resultado = memcmp(buf1, buf2, sizeof(buf1));<br />
Funciones relacionadas: memicmp.<br />
memcpy<br />
#inclu<strong>de</strong><br />
void *memcpy(void *<strong>de</strong>st, const void *fuente, size_t n);<br />
Copia n bytes <strong>de</strong> fuente en <strong>de</strong>st. Devuelve un puntero a <strong>de</strong>st.<br />
memcpy(<strong>de</strong>st, fuente, 80):<br />
Funciones relacionadas: memccpy, memmove, movedata.<br />
memset<br />
void *memset(void *s, int c, size_t n);<br />
Fija los n primeros bytes <strong>de</strong>l array s al carácter c.<br />
resultado = memset(buffer,´1´, 50);<br />
#inclu<strong>de</strong> <br />
Funciones relacionadas: memccpy, memcpy, memmove, movemem, setmem.<br />
movedata<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
void movedata (unsigned ss, unsigned so,<br />
unsigned ds, unsigned do, size_t n);<br />
Mueve n bytes <strong>de</strong>s<strong>de</strong> ss a ds, don<strong>de</strong> ss es el segmento fuente, so es el<br />
<strong>de</strong>splazamiento fuente, ds es el segmento <strong>de</strong>stino, do es el <strong>de</strong>splazamiento<br />
<strong>de</strong>stino y n es el número <strong>de</strong> bytes que hay que mover.<br />
movedata(seg1, off, seg2, <strong>de</strong>st_off, 4096);<br />
memicmp<br />
#inclu<strong>de</strong> <br />
#inclu<strong>de</strong> <br />
Funciones relacionadas: memcpy, memmove, movmem, segread.<br />
int memicmp (const void *b1, const void *b2, size_t n);<br />
movmem<br />
#inclu<strong>de</strong> <br />
Compara un número <strong>de</strong> bytes <strong>de</strong> un buffer (b1) con otro (b2) sin hacer<br />
caso <strong>de</strong>l tamaño <strong>de</strong> las letras en los dos buffers.<br />
if(memicmp(buf1, buf2, 15) == 0)<br />
puts(“Los buffers son iguales en los 15 primeros bytes \n”);<br />
Funciones relacionadas: memcmp.<br />
void movmem(void *fuente, void *<strong>de</strong>stino, unsigned n);<br />
Copia n bytes <strong>de</strong> fuente a <strong>de</strong>stino.<br />
movmem(&fuente[6], fuente, sizeof(fuente));<br />
Funciones relacionadas: memmove.
BIBLIOTECA DE FUNCIONES ESTÁNDAR <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0 661<br />
setmem<br />
#inclu<strong>de</strong> <br />
clrscr<br />
#inclu<strong>de</strong> <br />
void setmem(void *<strong>de</strong>st, unsigned long, char c);<br />
Fija un bloque <strong>de</strong> long bytes en el buffer <strong>de</strong>st al carácter c. setmem es<br />
útil para inicializar buffers.<br />
setmem(buffer, 60, ´t´);<br />
Funciones relacionadas: memset.<br />
void (clrscr(void);<br />
Borra la ventana actual y pone el cursor en la esquina superior izquierda<br />
(1,1).<br />
clrscr();<br />
Funciones relacionadas: clreol, textbackground, window.<br />
swab<br />
#inclu<strong>de</strong> <br />
<strong>de</strong>lline<br />
#inclu<strong>de</strong> <br />
void swab(char *fuente, char *<strong>de</strong>stino, int n);<br />
Copia un número par <strong>de</strong> bytes <strong>de</strong> una posición a otra, intercambiando al<br />
mismo tiempo cada par <strong>de</strong> bytes adyacentes.<br />
swab(“mnpq”, resultado, 4);<br />
// resultado es “nmpq”<br />
Funciones relacionadas: Sólo está disponible en sistemas UNIX.<br />
F.14.<br />
FUNCIONES DE PRESENTACIÓN DE TEXTO<br />
Las <strong>funciones</strong> <strong>de</strong> presentación <strong>de</strong> texto permiten <strong>de</strong>finir coor<strong>de</strong>nadas <strong>de</strong> una<br />
ventana <strong>de</strong> texto en la pantalla y manipular texto. Con estas <strong>funciones</strong> se<br />
pue<strong>de</strong> posicionar texto en cualquier parte <strong>de</strong> la pantalla, seleccionar atributos<br />
<strong>de</strong> texto (tales como subrayado, ví<strong>de</strong>o inverso, parpa<strong>de</strong>o, colores <strong>de</strong><br />
fondo y primer plano), así como actuar sobre ventanas <strong>de</strong> texto. Estas <strong>funciones</strong><br />
se encuentran esencialmente en el archivo <strong>de</strong> cabecera conio.h.<br />
void <strong>de</strong>lline(void);<br />
Borra la línea completa que contiene el cursor y <strong>de</strong>splaza hacia arriba<br />
las líneas que haya <strong>de</strong>bajo.<br />
<strong>de</strong>lline();<br />
Funciones relacionadas: clreol, clrscr.<br />
gettext<br />
#inclu<strong>de</strong> <br />
int gettext(int izda, int arriba, int <strong>de</strong>recha, int abajo,<br />
void *textbuf);<br />
Copia el contenido <strong>de</strong> un área rectangular <strong>de</strong> la pantalla al buffer cuya<br />
dirección se da en el argumento textbuf. Todas las coor<strong>de</strong>nadas son absolutas.<br />
if(!gettext(1,1,30,20, pan_grabada))<br />
puts(“color”);<br />
clreol<br />
#inclu<strong>de</strong> <br />
Funciones relacionadas: movetext, puttext.<br />
void clreol(void);<br />
Borra la línea actual <strong>de</strong>s<strong>de</strong> la posición <strong>de</strong>l cursor al final <strong>de</strong> la línea.<br />
clreol()<br />
Funciones relacionadas: clrscr, <strong>de</strong>lline, textbackground, window.<br />
gettextinfo<br />
void gettextinfo(struct text_info *r);<br />
#inclu<strong>de</strong> <br />
Devuelve información relativa a las coor<strong>de</strong>nadas <strong>de</strong> la ventana actual,<br />
posición <strong>de</strong>l cursor <strong>de</strong>ntro <strong>de</strong> la ventana, atributo <strong>de</strong>l texto, las dimensiones
662 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
<strong>de</strong> la pantalla y el modo <strong>de</strong> texto actual. La información se <strong>de</strong>vuelve en una<br />
estructura text_info.<br />
struct text_info {<br />
unsigned char winleft; // coor<strong>de</strong>nadas x, y esquina superior<br />
// izquierda<br />
unsigned char wintop; // ventana actual<br />
unsigned char winright; // coor<strong>de</strong>nadas x, y esquina inferior<br />
// <strong>de</strong>recha<br />
unsigned char winbottom; // ventana actual<br />
unsigned char attribute; // atributo texto actual<br />
unsigned char normattr; // atributo texto normal<br />
unsigned char currmo<strong>de</strong>; // modo texto actual<br />
unsigned char screenheight;// altura <strong>de</strong> la pantalla<br />
unsigned char screenwidth; // anchura pantalla<br />
unsigned char curx; // coor<strong>de</strong>nada x cursor<br />
unsigned char cury; // coor<strong>de</strong>nada y cursor<br />
};<br />
gotoxy<br />
void gotoxy(int x, int y);<br />
#inclu<strong>de</strong> <br />
Mueve el cursor a una posición especificada (columna x, fila y) <strong>de</strong>ntro<br />
<strong>de</strong> la ventana <strong>de</strong> texto actual.<br />
gotoxy(15, 4);<br />
Funciones relacionadas: wherex, wherey, window.<br />
Inserta una línea en blanco en la ventana <strong>de</strong> texto actual en la posición<br />
<strong>de</strong>l cursor, <strong>de</strong>splazando el resto <strong>de</strong> las líneas situadas <strong>de</strong>bajo.<br />
insline();<br />
Funciones relacionadas: clreol, <strong>de</strong>lline, window.<br />
lowvi<strong>de</strong>o<br />
void lowvi<strong>de</strong>o(void);<br />
Activa los caracteres a baja intensidad.<br />
lowvi<strong>de</strong>o();<br />
#inclu<strong>de</strong> <br />
Funciones relacionadas: highvi<strong>de</strong>o, normvi<strong>de</strong>o, textcolor.<br />
movetext<br />
#inclu<strong>de</strong> <br />
iont movetext(int izda, int arriba, int dcha,<br />
int abajo, int nuevoizda, int nuevoarriba);<br />
Copia el contenido <strong>de</strong> una zona rectangular <strong>de</strong> la pantalla (en modo<br />
texto) a otro rectángulo en la pantalla <strong>de</strong> las mismas dimensiones.<br />
if (!movetext(1, 1, 30, 20, 40, 40))<br />
puts(“victoria”);<br />
highvi<strong>de</strong>o<br />
#inclu<strong>de</strong> <br />
Funciones relacionadas: gettext, puttext.<br />
void highvi<strong>de</strong>o(void);<br />
Activa caracteres <strong>de</strong> alta intensidad.<br />
highvi<strong>de</strong>o();<br />
Funciones relacionadas: lowvi<strong>de</strong>o, normvi<strong>de</strong>o, textcolor.<br />
normvi<strong>de</strong>o<br />
void normvi<strong>de</strong>o(void);<br />
#inclu<strong>de</strong> <br />
Reinicializa los atributos <strong>de</strong> texto al valor que tenían antes <strong>de</strong> que arranque<br />
el programa.<br />
insline<br />
void insline(void);<br />
#inclu<strong>de</strong> <br />
normvi<strong>de</strong>o();<br />
Funciones relacionadas: highvi<strong>de</strong>o, lowvi<strong>de</strong>o, textattr, textcolor.
BIBLIOTECA DE FUNCIONES ESTÁNDAR <strong>ANSI</strong>/<strong>ISO</strong> <strong>C++</strong> Y BORLAND <strong>C++</strong> 5.0 663<br />
puttext<br />
#inclu<strong>de</strong> <br />
textbackground<br />
#inclu<strong>de</strong> <br />
int puttext(int izda, int arriba, int dcha, int abajo,<br />
void *textbuf);<br />
Copia el contenido <strong>de</strong> un buffer en una zona rectangular <strong>de</strong> la pantalla<br />
en modo texto.<br />
void textbackground(int colorfondo);<br />
Establece el color <strong>de</strong> fondo para texto vidualizado.<br />
textbackground(2);<br />
puttext(3, 1, 32, 22, buffertexto);<br />
Funciones relacionadas: gettext, movetext.<br />
textcolor<br />
#inclu<strong>de</strong> <br />
void textcolor(int colorprimerplano);<br />
_setcursortype<br />
void setcursortype(int estilo_cursor);<br />
#inclu<strong>de</strong> <br />
Establece el color <strong>de</strong>l primer plano <strong>de</strong>l texto visualizado por cprintf y<br />
cputs. El argumento pue<strong>de</strong> tomar un valor entre 0 BLACK (negro) y 15<br />
WHITE (blanco).<br />
Cambia la forma <strong>de</strong>l cursor en modo texto. El argumento tiene que ser<br />
una <strong>de</strong> las constantes.<br />
textcolor(15);t<br />
_NOCURSOR<br />
_SOLIDCURSOR<br />
_NORMALCURSOR<br />
Desactiva el cursor.<br />
Un carácter bloque sólido es el cursor.<br />
Un subrayado parpa<strong>de</strong>ante es el cursor.<br />
Funciones relacionadas: textattr, textbackground.<br />
setcursortype(_SOLIDCURSOR);<br />
Funciones relacionadas: cprintf, cputs.<br />
texmo<strong>de</strong><br />
void textmo<strong>de</strong>(int nuevomodo);<br />
#inclu<strong>de</strong> <br />
Conmuta al modo texto especificado por el argumento nuevomodo.<br />
textattr<br />
void textattr(int atrib);<br />
#inclu<strong>de</strong> <br />
Fija el atributo <strong>de</strong> texto a atrib. Se utiliza para controlar la apariencia<br />
<strong>de</strong>l texto en la pantalla.<br />
textattr(YELLOW + (RED
664 PROGRAMACIÓN EN <strong>C++</strong>. ALGORITMOS, ESTRUCTURAS Y OBJETOS<br />
wherex<br />
wherey<br />
int wherex(void);<br />
int wherey(void);<br />
#inclu<strong>de</strong> <br />
Determina la coor<strong>de</strong>nada x (wherex) y la coor<strong>de</strong>nada y (wherey) <strong>de</strong> la<br />
posición <strong>de</strong>l cursor en la ventana actual.<br />
xpos = where(x); ypos = where(y);<br />
window<br />
#inclu<strong>de</strong> <br />
void window(int izda, int arriba, int dcha, int abajo);<br />
Define una región rectangular <strong>de</strong> la pantalla como la ventana <strong>de</strong> texto<br />
actual esquina superior izquierda (izda, arriba) y esquina inferior <strong>de</strong>recha<br />
(dcha, abajo).<br />
window(15, 5, 54, 14);<br />
// ventana <strong>de</strong> 40 x 10 con origen en (15, 5)<br />
Funciones relacionadas: gettextinfo, textmo<strong>de</strong>.