#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Estructura para el índice
struct Indice {
char clave[20];
long posicion;
};
// Función para crear el índice
void crearIndice(FILE *archivo, FILE *indice) {
struct Indice registro;
long posicion = 0;
while (fread(®istro, sizeof(struct Indice), 1, archivo) == 1) {
fseek(indice, 0, SEEK_END);
strcpy(registro.clave, strlwr(registro.clave)); // Convertir la clave a minúsculas
registro.posicion = posicion;
fwrite(®istro, sizeof(struct Indice), 1, indice);
posicion++;
}
}
// Función para buscar un registro por clave
void buscarRegistro(FILE *archivo, FILE *indice, char *clave) {
struct Indice registro;
int encontrado = 0;
fseek(indice, 0, SEEK_SET);
while (fread(®istro, sizeof(struct Indice), 1, indice) == 1) {
if (strcmp(strlwr(registro.clave), strlwr(clave)) == 0) { // Comparar claves en minúsculas
fseek(archivo, registro.posicion * sizeof(struct Indice), SEEK_SET);
fread(®istro, sizeof(struct Indice), 1, archivo);
printf("Registro encontrado:\n");
printf("Clave: %s\n", registro.clave);
printf("Posición: %ld\n", registro.posicion);
encontrado = 1;
break;
}
}
if (!encontrado) {
printf("Registro no encontrado.\n");
}
}
int main() {
FILE *archivo, *indice;
char clave[20];
archivo = fopen("datos.dat", "rb");
indice = fopen("indice.dat", "wb");
if (archivo == NULL || indice == NULL) {
printf("Error al abrir los archivos.\n");
return 1;
}
crearIndice(archivo, indice);
printf("Ingrese la clave a buscar: ");
scanf("%s", clave);
buscarRegistro(archivo, indice, clave);
fclose(archivo);
fclose(indice);
return 0;
}