• Sábado 27 de Abril de 2024, 05:55

Autor Tema:  Ordenacion De Registros  (Leído 2988 veces)

cybergatita

  • Miembro MUY activo
  • ***
  • Mensajes: 154
    • Ver Perfil
Ordenacion De Registros
« en: Martes 13 de Junio de 2006, 20:52 »
0
Que tal compañeros!!!!


Alguien ah utilizado alguna función pre-definida para la ordenacion de registros trabajando con archivos en C++ y obviamente punteros.
en la imagen que anexo esta como estoy visualizando mis registros con los datos
los cuales quisiera ordenar alfabeticamente.



gracias chicos.
El mensaje contiene 1 archivo adjunto. Debes ingresar o registrarte para poder verlo y descargarlo.

tonilope

  • Miembro activo
  • **
  • Mensajes: 51
    • Ver Perfil
Re: Ordenacion De Registros
« Respuesta #1 en: Martes 13 de Junio de 2006, 21:28 »
0
Tienes la función qsort() -> http://c.conclase.net/librerias/funcion.php?fun=qsort

Salu2 ;)

cybergatita

  • Miembro MUY activo
  • ***
  • Mensajes: 154
    • Ver Perfil
Re: Ordenacion De Registros
« Respuesta #2 en: Martes 13 de Junio de 2006, 21:51 »
0
Gracias la estoy checando.

tonilope

  • Miembro activo
  • **
  • Mensajes: 51
    • Ver Perfil
Re: Ordenacion De Registros
« Respuesta #3 en: Martes 13 de Junio de 2006, 21:55 »
0
Si te lías con ese ejemplo:

Salu2 ;)

bob esponja

  • Miembro MUY activo
  • ***
  • Mensajes: 411
    • Ver Perfil
    • http://marianoguerra.blogspot.com
Re: Ordenacion De Registros
« Respuesta #4 en: Martes 13 de Junio de 2006, 23:07 »
0
ORDENAMIENTO!  :smartass:

cybergatita

  • Miembro MUY activo
  • ***
  • Mensajes: 154
    • Ver Perfil
Re: Ordenacion De Registros
« Respuesta #5 en: Martes 13 de Junio de 2006, 23:11 »
0
gracias por su ayuda.


char nombre[50];
int digito[10];



void Listar2(long n, struct stRegistro *reg)
{
int i;
if(reg->valido!='S')
{
printf("[%6ld]%-50s",n,reg->nombre);
for(i=0;i<4;i++)
printf(",%4d",reg->digotp);
printf("\n");




lo que yo quiero ordenar es el nombre del registro no los datos del registro



asi es como lo muestro


printf("Nombre                             digito\n");

while(fread(®, sizeof(struct stRegistro), 1, fa))
      Listar(numero++, ®);
}while(!eof);



no se si me di entender y como veran algo novata, vdd:(

tonilope

  • Miembro activo
  • **
  • Mensajes: 51
    • Ver Perfil
Re: Ordenacion De Registros
« Respuesta #6 en: Miércoles 14 de Junio de 2006, 01:28 »
0
Hola. Por lo que puedo entender tienes un fichero con registros del tipo struct stRegistro y leyendo el código (incompleto) que has puesto intuyo que tienes definida una estructura así:

Código: Text
  1.  
  2. struct stRegistro
  3. {
  4. char nombre[50];
  5. int digito;
  6. };
  7.  
  8.  

Si esto es correcto y lo que pretendes es MOSTRAR por PANTALLA una lista del tipo:

Juan 1
Antonio 34
Rosa 7
Marcos 23
ETC...


ORDENADA alfabéticamente por el nombre:
Antonio 34
Juan 1
Marcos 23
Rosa 7
ETC...


TIENES que:

1) Declarar un array de tipo struct stRegistro para 10 (o los que necesites) elementos:
Código: Text
  1.  
  2. struct stRegistro array[10];
  3.  
  4.  

2) Leer TODOS los registros del fichero y cargarlos en el array

Código: Text
  1.  
  2.  
  3. conta=0;
  4.  
  5. while (fread(&array[conta], 1, sizeof(struct stRegistro), puntero_fichero) &#62; 0)
  6. {
  7.  
  8. conta++;
  9.  
  10. }
  11.  
  12.  
  13.  

3) Una vez tienes la lista cargada en el array, la ordenas:

Código: Text
  1.  
  2. qsort((void*)array, 10, sizeof(struct stRegistro), comparar);
  3.  
  4.  

4) Finalmente la muestras ordenada por pantalla:

Código: Text
  1.  
  2. for(conta=0; conta&#60;10; conta++)
  3. printf(&#34;&#092;n%s&#092;t%d&#34;, array[conta].nombre, array[conta].digito);
  4.  
  5.  

Ejemplo completo:

Código: Text
  1.  
  2.  
  3. #include &#60;stdio.h&#62;
  4. #include &#60;stdlib.h&#62;
  5. #include &#60;string.h&#62;
  6.  
  7. #define NUM_ELEMENTOS 10
  8.  
  9. struct stRegistro
  10. {
  11.  
  12. char nombre[50];
  13. int digito;
  14.  
  15. };
  16.  
  17.  
  18. int comparar(const void *, const void *);
  19.  
  20.  
  21.  
  22.  
  23. int main(int argc, char **argv)
  24. {
  25.  
  26. struct stRegistro array[NUM_ELEMENTOS];
  27. int conta;
  28. FILE *puntero_fichero;
  29.  
  30. puntero_fichero=fopen(&#34;fichero.dat&#34;, &#34;rb&#34;);
  31. conta=0;
  32. while (fread(&array[conta], 1, sizeof(struct stRegistro), puntero_fichero) &#62; 0)
  33. {
  34.  
  35. conta++;
  36.  
  37. }
  38.  
  39. fclose(puntero_fichero);
  40.  
  41. printf(&#34;&#092;n&#092;nLa lista original:&#092;n&#34;);
  42.  
  43. for(conta=0; conta&#60;NUM_ELEMENTOS; conta++)
  44. printf(&#34;&#092;n%s&#092;t%d&#34;, array[conta].nombre, array[conta].digito);
  45.  
  46. qsort((void*)array, NUM_ELEMENTOS, sizeof(struct stRegistro), comparar);
  47.  
  48. printf(&#34;&#092;n&#092;nLa lista ordenada:&#092;n&#34;);
  49.  
  50. for(conta=0; conta&#60;NUM_ELEMENTOS; conta++)
  51. printf(&#34;&#092;n%s&#092;t%d&#34;, array[conta].nombre, array[conta].digito);
  52.  
  53. return 0;
  54.  
  55. }
  56.  
  57. int comparar(const void *arg1, const void *arg2)
  58. {
  59.  
  60. return strcmp(((struct stRegistro*)arg1)-&#62;nombre, ((struct stRegistro*)arg2)-&#62;nombre);
  61.  
  62. }
  63.  
  64.  

Adjunto un fichero que he creado con 10 registros para probar este código.

Salu2 ;)
El mensaje contiene 1 archivo adjunto. Debes ingresar o registrarte para poder verlo y descargarlo.

cybergatita

  • Miembro MUY activo
  • ***
  • Mensajes: 154
    • Ver Perfil
Re: Ordenacion De Registros
« Respuesta #7 en: Miércoles 14 de Junio de 2006, 02:18 »
0
hola tonilope


estoy implementando tu ejemplo a mi codigo, pero tengo algo mal

angie_lozca@hotmail.com

saludos,

tonilope

  • Miembro activo
  • **
  • Mensajes: 51
    • Ver Perfil
Re: Ordenacion De Registros
« Respuesta #8 en: Miércoles 14 de Junio de 2006, 02:43 »
0
Pon aquí el problema que tengas.

Salu2 ;)

cybergatita

  • Miembro MUY activo
  • ***
  • Mensajes: 154
    • Ver Perfil
Re: Ordenacion De Registros
« Respuesta #9 en: Miércoles 14 de Junio de 2006, 03:50 »
0
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <io.h>


struct stRegistro
{
char valido; //campo que indica si el registro es valido S->Valido, N->Invalido
char nombre[34];
int dato[4];
};

struct stRegistro array[5];

int comparar(const void *, const void *);

int Menu();
void Leer(struct stRegistro *reg);
void Mostrar(struct stRegistro *reg);
void Listar(long n,struct stRegistro *reg);
void Listar2(long n,struct stRegistro *reg);

long LeeNumero();
void Empaquetar(FILE **fa);

int main()
{
struct stRegistro reg;
FILE *fa;
int opcion;
long numero;
fa=fopen("alea.dat","r+b"); //este modo permite leer y escribir
if(!fa)fa=fopen("alea.dat","w+b"); //si el fichero no existe, lo crea
do
{
opcion=Menu();


switch(opcion)
{


case'1': //añadir registro
Leer(®);
//insertar al final;
fseek(fa,0,SEEK_END);
fwrite(®,sizeof(struct stRegistro),1,fa);
break;


case'2': //mostrar registro
clrscr();//system("cls");
printf("Mostrar registro:");
numero=LeeNumero();
fseek(fa,numero*sizeof(struct stRegistro),SEEK_SET);
fread(®,sizeof(struct stRegistro),1,fa);
Mostrar(®);
break;


case'3': // eliminar registro
clrscr();//system("cls");
printf("Eliminar registro:");
numero=LeeNumero();
fseek(fa,numero*sizeof(struct stRegistro),SEEK_SET);
fread(®,sizeof(struct stRegistro),1,fa);
reg.valido='N';
fseek(fa,numero*sizeof(struct stRegistro),SEEK_SET);
fwrite(®,sizeof(struct stRegistro),1,fa);
break;


case'4': //mostrar todo
rewind(fa);
   numero = 0;
//system("cls");

   do{
clrscr();
printf("Nombre                             Calificacion\n");

while(fread(®, sizeof(struct stRegistro), 1, fa))
      Listar(numero++, ®);
}while(!eof);
//system("PAUSE");
getch();

int conta=0;

while (fread(&array[conta], 1, sizeof(struct stRegistro), *reg) > 0)

{

conta++;

}


qsort((void*)array, 5, sizeof(struct stRegistro), comparar);
for(conta=0; conta<5; conta++)
printf("\n%s\t%d", array[conta].nombre, array[conta].dato);

getch();

break;

case'5': // eliminar marcados
Empaquetar(&fa);
break;


case'6':
rewind(fa);
numero=0;
clrscr();//system("cls");
printf("Nombre            Datos\n");
while(fread(®,sizeof(struct stRegistro),1,fa));
Listar2(numero++,®);
getch(); //system("PAUSE");
break;
}
}while(opcion!='0');
fclose(fa);
return 0;
}


// Muestra un menu con las opciones disponibles y captura una opcion del usuario


int Menu()

{

char resp[20];
do

{

clrscr();//system("cls");
printf("MENU PRINCIPAL\n");
printf("--------\n\n");
printf("1-Insertar registro\n");
printf("2-Mostrar registro\n");
printf("3-Eliminar registro\n");
printf("4-Mostrar todo\n");
printf("5-Eliminar registro marcados\n");
printf("6-Mostrar lista de disponibles\n");
printf("0-Salir\n");
fgets(resp,20,stdin);
 }  while(resp[0]<'0'&&resp[0]>'6');
  return resp[0];
}


// permite que el usuario introduzca un registro por pantalla
void Leer(struct stRegistro *reg)

{
int i;
char numero[6];
clrscr();// system("cls");
printf("Leer registro:\n\n");
reg->valido='S';
printf("Nombre:");
fgets(reg->nombre,34,stdin);
// la funcion fgets captura el retorno de linea, hay que eliminarlo:
for(i=strlen(reg->nombre)-1;i&®->nombre <' ';i--)
reg->nombre=0;
for(i=0;i<4;i++)
{
printf("Calificacion[%1d]:",i);
fgets(numero,6,stdin);
reg->dato=atoi(numero);
 }
}
// muestra un registro en pantalla, si no esta marcado como borrado
void Mostrar(struct stRegistro *reg)
{
int i;
clrscr();//system("cls");
if(reg->valido=='S')
{
printf("Nombre: %s\n",reg->nombre);
for(i=0;i<4;i++)
printf("Calificacion[%1d]:%d\n",i,reg->dato);
}
i++;
getch();//system("PAUSE");
}
// muestra un registro por pantalla en forma de listado, si no esta marcado como borrado

void Listar2(long n, struct stRegistro *reg)
{
int i;
if(reg->valido!='S')
{
printf("[%6ld]%-34s",n,reg->nombre);
for(i=0;i<4;i++)
printf(",%4d",reg->dato);
printf("\n");
 }
}



void Listar(long n, struct stRegistro *reg)
{
int i;
if(reg->valido=='S')
{
printf("[%6ld]%-34s",n,reg->nombre);
for(i=0;i<4;i++)
printf(",%4d",reg->dato);
printf("\n");
 }
}
// lee un numero suministrado por el usuario
long LeeNumero()
{
char numero[6];
fgets(numero,6,stdin);
return atoi(numero);
}
// elimina los registros marcados como borrados
void Empaquetar(FILE**fa)
{
FILE*ftemp;
struct stRegistro reg;
ftemp=fopen("alea.tmp","wb");
rewind(*fa);
while(fread(®,sizeof(struct stRegistro),1,*fa));
if(reg.valido=='S')
fwrite(®,sizeof(struct stRegistro),1,ftemp);
fclose(ftemp);
fclose(*fa);
remove("alea.bak");
rename("alea.dat","alea.bak");
rename("alea.tmp","alea.dat");
*fa=fopen("alea.dat","r+b");
}



hola


aqui esta mi gran problema

gracias de antemano toni!!!!

cybergatita

  • Miembro MUY activo
  • ***
  • Mensajes: 154
    • Ver Perfil
Re: Ordenacion De Registros
« Respuesta #10 en: Miércoles 14 de Junio de 2006, 04:08 »
0
en el case 4 trate de implementar lo que me comentaste. y me manda un error
:(
delo contrario pues si corre:)

tonilope

  • Miembro activo
  • **
  • Mensajes: 51
    • Ver Perfil
Re: Ordenacion De Registros
« Respuesta #11 en: Miércoles 14 de Junio de 2006, 18:48 »
0
He hecho un par de correciones rápidas muy POR ENCIMA y funciona. Aquí te lo dejo:

Código: Text
  1.  
  2. #include &#60;stdio.h&#62;
  3. #include &#60;stdlib.h&#62;
  4. #include &#60;string.h&#62;
  5.  
  6. struct stRegistro
  7. {
  8. char valido; //campo que indica si el registro es valido S-&#62;Valido, N-&#62;Invalido
  9. char nombre[34];
  10. int dato[4];
  11. };
  12.  
  13. int comparar(const void *, const void *);
  14.  
  15. int Menu();
  16. void Leer(struct stRegistro *reg);
  17. void Mostrar(struct stRegistro *reg);
  18. void Listar(long n,struct stRegistro *reg);
  19. long LeeNumero();
  20. void Empaquetar(FILE **fa);
  21.  
  22. int main()
  23. {
  24. struct stRegistro reg;
  25. struct stRegistro *array;
  26. FILE *fa;
  27. int opcion, total_registros;
  28. long numero, conta;
  29. fa=fopen(&#34;alea.dat&#34;,&#34;r+b&#34;); //este modo permite leer y escribir
  30. if(!fa)fa=fopen(&#34;alea.dat&#34;,&#34;w+b&#34;); //si el fichero no existe, lo crea
  31. do
  32. {
  33. opcion=Menu();
  34.  
  35.  
  36. switch(opcion)
  37. {
  38.  
  39.  
  40. case'1': //añadir registro
  41. Leer(&reg);
  42. //insertar al final;
  43. fseek(fa,0,SEEK_END);
  44. fwrite(&reg,1,sizeof(struct stRegistro),fa);
  45. break;
  46.  
  47.  
  48. case'2': //mostrar registro
  49. system(&#34;cls&#34;);//system(&#34;cls&#34;);
  50. printf(&#34;Mostrar registro:&#34;);
  51. numero=LeeNumero();
  52. fseek(fa,numero*sizeof(struct stRegistro),SEEK_SET);
  53. fread(&reg,1,sizeof(struct stRegistro),fa);
  54. Mostrar(&reg);
  55. break;
  56.  
  57.  
  58. case'3': // eliminar registro
  59. system(&#34;cls&#34;);//system(&#34;cls&#34;);
  60. rewind(fa);
  61.  
  62.  
  63. total_registros=0;
  64. system(&#34;cls&#34;);
  65. printf(&#34;Nombre Calificacion&#092;n&#34;);
  66.  
  67. while(fread(&reg,1, sizeof(struct stRegistro), fa)&#62;0)
  68.      {
  69.      total_registros++;
  70.      }
  71.  
  72. array=(struct stRegistro*)malloc(total_registros*sizeof(struct stRegistro));
  73.  
  74. rewind(fa);
  75.  
  76. conta=0;
  77. while(fread(&array[conta++],1, sizeof(struct stRegistro), fa)&#62;0);
  78.  
  79. for(conta=0; conta&#60;total_registros; conta++)
  80.      Listar(conta, &array[conta]);
  81.  
  82. free(array);
  83.  
  84. printf(&#34;Eliminar registro:&#34;);
  85. numero=LeeNumero();
  86. fseek(fa,numero*sizeof(struct stRegistro),SEEK_SET);
  87. fread(&reg,1,sizeof(struct stRegistro),fa);
  88. reg.valido='N';
  89. fseek(fa,numero*sizeof(struct stRegistro),SEEK_SET);
  90. fwrite(&reg,1,sizeof(struct stRegistro),fa);
  91. break;
  92.  
  93.  
  94. case'4': //mostrar todo
  95. rewind(fa);
  96.  
  97.  
  98. total_registros=0;
  99. system(&#34;cls&#34;);
  100. printf(&#34;Nombre Calificacion&#092;n&#34;);
  101.  
  102. while(fread(&reg,1, sizeof(struct stRegistro), fa)&#62;0)
  103.      {
  104.      total_registros++;
  105.      }
  106.  
  107. array=(struct stRegistro*)malloc(total_registros*sizeof(struct stRegistro));
  108.  
  109. rewind(fa);
  110.  
  111. conta=0;
  112. while(fread(&array[conta++],1, sizeof(struct stRegistro), fa)&#62;0);
  113.  
  114. qsort((void*)array, total_registros, sizeof(struct stRegistro), comparar);
  115.  
  116. for(conta=0; conta&#60;total_registros; conta++)
  117.      Listar(conta, &array[conta]);
  118.      
  119. getch();
  120.  
  121. free(array);
  122. break;
  123.  
  124. case'5': // eliminar marcados
  125. Empaquetar(&fa);
  126. break;
  127.  
  128. //NO entiendo para qué vale este case
  129. /*
  130. case'6':
  131. rewind(fa);
  132. numero=0;
  133. system(&#34;cls&#34;);//system(&#34;cls&#34;);
  134. printf(&#34;Nombre Datos&#092;n&#34;);
  135. while(fread(&reg,sizeof(struct stRegistro),1,fa));
  136. Listar(numero++,&reg);
  137. getch(); //system(&#34;PAUSE&#34;);
  138. break;
  139. */
  140.  
  141. }
  142. }while(opcion!='0');
  143. fclose(fa);
  144. return 0;
  145. }
  146.  
  147.  
  148. // Muestra un menu con las opciones disponibles y captura una opcion del usuario
  149.  
  150.  
  151. int Menu()
  152.  
  153. {
  154.  
  155. char resp[20];
  156. do
  157.  
  158. {
  159.  
  160. system(&#34;cls&#34;);//system(&#34;cls&#34;);
  161. printf(&#34;MENU PRINCIPAL&#092;n&#34;);
  162. printf(&#34;--------&#092;n&#092;n&#34;);
  163. printf(&#34;1-Insertar registro&#092;n&#34;);
  164. printf(&#34;2-Mostrar registro&#092;n&#34;);
  165. printf(&#34;3-Eliminar registro&#092;n&#34;);
  166. printf(&#34;4-Mostrar todo&#092;n&#34;);
  167. printf(&#34;5-Eliminar registro marcados&#092;n&#34;);
  168. printf(&#34;6-Mostrar lista de disponibles&#092;n&#34;);
  169. printf(&#34;0-Salir&#092;n&#34;);
  170. resp[0]=getch();
  171. } while(resp[0]&#60;'0'&&resp[0]&#62;'6');
  172. return resp[0];
  173. }
  174.  
  175.  
  176. // permite que el usuario introduzca un registro por pantalla
  177. void Leer(struct stRegistro *reg)
  178.  
  179. {
  180. int i;
  181. char numero[6];
  182. system(&#34;cls&#34;);// system(&#34;cls&#34;);
  183. printf(&#34;Leer registro:&#092;n&#092;n&#34;);
  184. reg-&#62;valido='S';
  185. printf(&#34;Nombre:&#34;);
  186. fgets(reg-&#62;nombre,34,stdin);
  187. // la funcion fgets captura el retorno de linea, hay que eliminarlo:
  188. for(i=strlen(reg-&#62;nombre)-1;i&&reg-&#62;nombre[i] &#60;' ';i--)
  189. reg-&#62;nombre[i]=0;
  190. for(i=0;i&#60;4;i++)
  191. {
  192. printf(&#34;Calificacion[%1d]:&#34;,i);
  193. fgets(numero,6,stdin);
  194. reg-&#62;dato[i]=atoi(numero);
  195. }
  196. }
  197.  
  198.  
  199. // muestra un registro en pantalla, si no esta marcado como borrado
  200. void Mostrar(struct stRegistro *reg)
  201. {
  202. int i;
  203. system(&#34;cls&#34;);//system(&#34;cls&#34;);
  204. if(reg-&#62;valido=='S')
  205. {
  206. printf(&#34;Nombre: %s&#092;n&#34;,reg-&#62;nombre);
  207. for(i=0;i&#60;4;i++)
  208. printf(&#34;Calificacion[%1d]:%d&#092;n&#34;,i,reg-&#62;dato[i]);
  209. }
  210. i++;
  211. getch();//system(&#34;PAUSE&#34;);
  212. }
  213.  
  214.  
  215.  
  216.  
  217.  
  218. void Listar(long n, struct stRegistro *reg)
  219. {
  220. int i;
  221. if(reg-&#62;valido=='S')
  222. {
  223. printf(&#34;[%6ld]%-34s&#34;,n,reg-&#62;nombre);
  224. for(i=0;i&#60;4;i++)
  225. printf(&#34;,%4d&#34;,reg-&#62;dato[i]);
  226. printf(&#34;&#092;n&#34;);
  227. }
  228.  
  229. }
  230. // lee un numero suministrado por el usuario
  231. long LeeNumero()
  232. {
  233. char numero[6];
  234. fgets(numero,6,stdin);
  235. return atoi(numero);
  236. }
  237. // elimina los registros marcados como borrados
  238. void Empaquetar(FILE**fa)
  239. {
  240. FILE *ftemp;
  241. struct stRegistro reg;
  242.  
  243. ftemp=fopen(&#34;alea.tmp&#34;,&#34;wb&#34;);
  244.  
  245. rewind(*fa);
  246.  
  247. while(fread(&reg,1,sizeof(struct stRegistro),*fa)&#62;0)
  248. {
  249.  
  250. if(reg.valido=='S')
  251. fwrite(&reg,sizeof(struct stRegistro),1,ftemp);
  252.  
  253. }
  254.  
  255. fclose(ftemp);
  256. fclose(*fa);
  257.  
  258. remove(&#34;alea.bak&#34;);
  259. rename(&#34;alea.dat&#34;,&#34;alea.bak&#34;);
  260. rename(&#34;alea.tmp&#34;,&#34;alea.dat&#34;);
  261.  
  262. *fa=fopen(&#34;alea.dat&#34;,&#34;r+b&#34;);
  263. }
  264. int comparar(const void *arg1, const void *arg2)
  265. {
  266.  
  267. return strcmp(((struct stRegistro*)arg1)-&#62;nombre, ((struct stRegistro*)arg2)-&#62;nombre);
  268.  
  269. }
  270.  
  271.  

Salu2 ;)

cybergatita

  • Miembro MUY activo
  • ***
  • Mensajes: 154
    • Ver Perfil
Re: Ordenacion De Registros
« Respuesta #12 en: Miércoles 14 de Junio de 2006, 23:10 »
0
Muchas gracias toni, ya lo implemente

ahora me falta añadirle un par de cosas mas a mi codigo, ya te contare como me fue




gracias de antemano a sus respuestas.