← C EspañolChapter 12 of 13

Biblioteca Estándar

## Objetivos de Aprendizaje - Dominar funciones comunes de la biblioteca estándar - Comprender funciones de entrada/salida - Trabajar con funciones de cadenas - Usar funciones de memoria y utilidad ## Encabezados Estándar | Encabezado | Descripción | |------------|-------------| | `` | Entrada/salida | | `` | Memoria, utilidades | | `` | Funciones de cadenas | | `` | Clasificación de caracteres | | `` | Funciones matemáticas | | `` | Fecha/hora | | `` | Aserciones | | `` | Límites de tipos | | `` | Límites de flotantes | ## stdio.h - Entrada/Salida ### Familia Printf ```c #include printf("Hello\n"); fprintf(fp, "Hello\n"); sprintf(buf, "Hello\n"); // A cadena snprintf(buf, size, "Hello\n"); // Seguro ``` ### Familia Scanf ```c int x; scanf("%d", &x); fscanf(fp, "%d", &x); sscanf(str, "%d", &x); ``` ### E/S de Caracteres ```c int getchar(void); // Leer char desde stdin int putchar(int c); // Escribir char a stdout int getc(FILE *fp); // Leer char desde archivo int putc(int c, FILE *fp); // Escribir char a archivo ``` ## stdlib.h - Utilidades ### Asignación de Memoria ```c void *malloc(size_t size); void *calloc(size_t nmemb, size_t size); void *realloc(void *ptr, size_t size); void free(void *ptr); ``` ### Control del Programa ```c #include exit(0); // Salir con éxito exit(1); // Salir con fracaso int atexit(void (*function)(void)); // Registrar función a llamar al salir void abort(void); // Terminación anormal ``` ### Conversión de Cadenas ```c int atoi(const char *str); // ASCII a int long atol(const char *str); // ASCII a long double atof(const char *str); // ASCII a float // Versiones más seguras int strtol(const char *str, char **endptr, int base); double strtod(const char *str, char **endptr); ``` ### Sistema ```c #include int system(const char *command); // Ejecutar comando de shell char *getenv(const char *name); // Obtener variable de entorno ``` ### Ordenamiento ```c void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)); int compare(const void *a, const void *b) { return (*(int*)a - *(int*)b); } int arr[] = {3, 1, 4, 1, 5}; qsort(arr, 5, sizeof(int), compare); ``` ### Búsqueda Binaria ```c void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)); int key = 4; int *result = (int*)bsearch(&key, arr, 5, sizeof(int), compare); ``` ### Números Aleatorios ```c #include int rand(void); void srand(unsigned int seed); // 0 a RAND_MAX int r = rand() % 100; // 0 a 99 ``` ### Valor Absoluto ```c #include int abs(int x); long labs(long x); ``` ## string.h - Funciones de Cadenas ### strlen ```c #include size_t strlen(const char *s); ``` ### Funciones de Copia ```c char *strcpy(char *dest, const char *src); char *strncpy(char *dest, const char *src, size_t n); void *memcpy(void *dest, const void *src, size_t n); void *memmove(void *dest, const void *src, size_t n); ``` ### Concatenación ```c char *strcat(char *dest, const char *src); char *strncat(char *dest, const char *src, size_t n); ``` ### Comparación ```c int strcmp(const char *s1, const char *s2); int strncmp(const char *s1, const char *s2, size_t n); int memcmp(const void *s1, const void *s2, size_t n); ``` ### Búsqueda ```c char *strchr(const char *s, int c); // Encontrar carácter char *strstr(const char *haystack, const char *needle); // Encontrar subcadena ``` ### Otras ```c void *memset(void *s, int c, size_t n); // Llenar memoria char *strerror(int errnum); // Mensaje de error size_t strcspn(const char *s, const char *reject); // Span hasta rechazar ``` ## ctype.h - Clasificación de Caracteres ```c #include int isalpha(int c); // Letra int isdigit(int c); // Dígito int isalnum(int c); // Letra o dígito int isspace(int c); // Espacio en blanco int isupper(int c); // Mayúscula int islower(int c); // Minúscula int iscntrl(int c); // Carácter de control int tolower(int c); // A minúscula int toupper(int c); // A mayúscula ``` ## math.h - Funciones Matemáticas ```c #include double sqrt(double x); double pow(double x, double y); double exp(double x); double log(double x); double log10(double x); double sin(double x); double cos(double x); double tan(double x); double ceil(double x); // Redondear hacia arriba double floor(double x); // Redondear hacia abajo double fabs(double x); // Valor absoluto double M_PI; // constante pi ``` ### Vincular con -lm ```bash gcc program.c -lm ``` ## time.h - Fecha y Hora ```c #include time_t now = time(NULL); // Hora actual printf("%s", ctime(&now)); struct tm *t = localtime(&now); printf("%d-%02d-%02d\n", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday); ``` ### Formateo ```c #include time_t now = time(NULL); char buf[100]; strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", localtime(&now)); printf("%s\n", buf); ``` ## Patrones Comunes ### Copia de Cadena Segura ```c char *safeCopy(char *dest, const char *src, size_t size) { if (size == 0) return dest; dest[0] = '\0'; strncat(dest, src, size - 1); return dest; } ``` ### Analizar Argumentos de Línea de Comandos ```c int main(int argc, char *argv[]) { for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "-n") == 0) { // Manejar bandera -n } else { // Manejar nombre de archivo } } return 0; } ``` ### Leer Archivo a Cadena ```c #include #include char *readFile(const char *filename) { FILE *fp = fopen(filename, "r"); if (!fp) return NULL; fseek(fp, 0, SEEK_END); long size = ftell(fp); rewind(fp); char *content = malloc(size + 1); if (!content) { fclose(fp); return NULL; } fread(content, 1, size, fp); content[size] = '\0'; fclose(fp); return content; } ``` ## Resumen - ``: printf, scanf, fprintf, fscanf, fopen, fclose - ``: malloc, free, calloc, realloc, atoi, strtol, qsort, exit - ``: strlen, strcpy, strncpy, strcat, strcmp, strncmp, memset, memcpy - ``: isalpha, isdigit, isspace, toupper, tolower - ``: sqrt, pow, sin, cos, ceil, floor (vincular con -lm) - ``: time, localtime, strftime - Siempre verificar valores de retorno de funciones para errores

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →