Share Pastebin
Guest
Public paste!

ejemplo de archivos en C

By: a guest | Mar 17th, 2010 | Syntax: C++ | Size: 1.68 KB | Hits: 160 | Expires: Never
Copy text to clipboard
  1. #include <stdio.h>
  2. #include <conio.h>
  3. #include <string.h>
  4. #include <stdlib.h>
  5.  
  6. struct comedor
  7. {
  8. char cedula[9];
  9. char nombre[20];
  10. char direccion[30];
  11. char fecha[9];
  12. int valido;
  13. }gente;
  14.  
  15. void ingresar();
  16. void mostrar();
  17.  
  18.  
  19. FILE *punt_arch;
  20.  
  21. void main()
  22. {
  23. int opc=0;
  24. while(opc!=3)
  25. {
  26. fflush(stdin);
  27. clrscr();
  28. printf("\t\t***MENU***\n\t1.-Ingresar Usuario\n\t2.-Mostrar todos los usuarios\n\t3.-Salir\n\tIngrese su opcion: ");
  29. scanf("%d",&opc);
  30. fflush(stdin);
  31. switch(opc)
  32. {
  33. case 1:
  34. ingresar();
  35. break;
  36. case 2:
  37. mostrar();
  38. break;
  39.  
  40. }
  41. }
  42. clrscr();
  43. printf("\t\tPOWERED BY ANDRES");
  44. getch();
  45.  
  46. }
  47.  
  48. void ingresar()
  49. {
  50. punt_arch=fopen("comedor.bin","a+b");
  51. long int ced;
  52.  
  53. printf("\n\tingrese la cedula: ");
  54. gets(gente.cedula);
  55. printf("\n\tingrese el nombre: ");
  56. gets(gente.nombre);
  57. printf("\n\tingrese la direccion: ");
  58. gets(gente.direccion);
  59. printf("\n\tIngrese la fecha (DDMMAAAA): ");
  60. gets(gente.fecha);
  61. gente.valido=1;
  62. ced=atol(gente.cedula);
  63. fseek(punt_arch,(ced*sizeof(comedor)),SEEK_END);
  64. fwrite(&gente,sizeof(struct comedor),1,punt_arch);
  65. fclose(punt_arch);
  66. fflush(stdin);
  67. }
  68.  
  69. void mostrar()
  70. {
  71. punt_arch=fopen("comedor.bin","r+b");
  72.  
  73. int vacio=0;
  74.  
  75. fflush(stdin);
  76. fseek(punt_arch,0,SEEK_SET);
  77. while(fread(&gente, sizeof(struct comedor), 1, punt_arch))
  78. {
  79. if(gente.valido==1)
  80. {
  81. printf("\n\tCedula: ");
  82. puts(gente.cedula);
  83. printf("\n\tNombre: ");
  84. puts(gente.nombre);
  85. printf("\n\tDireccion: ");
  86. puts(gente.direccion);
  87. printf("\n\tFecha de ingreso al comedor: ");
  88. puts(gente.fecha);
  89. getch();
  90. printf("\t.....................................");
  91. vacio=1;
  92. }
  93. }
  94. if(vacio==0)
  95. {
  96. printf("\tNo hay nadie registrado");
  97. getch();
  98. }
  99. fclose(punt_arch);
  100. }