Advertisement
AntonioVillanueva

Ficheros y estructuras

Mar 18th, 2016
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.69 KB | None | 0 0
  1. //compilacion g++ -std=c++11 -o NombreEjecutable NombreFuente.cpp
  2.  
  3. /* fread example: read an entire file */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <iostream>
  7. using namespace std;
  8.  
  9. typedef struct alum {int clave;string nombre;}__ALUMNO__;
  10.  
  11. void escribe()
  12. {
  13.  
  14.     __ALUMNO__ alumno;
  15.  
  16.     //FILE* fp = fopen( "alumnos.txt", "wb+" );
  17.  
  18.     FILE* fp = fopen( "alumnos.txt", "a+" );   
  19.    
  20.     alumno.clave = 666;
  21.     alumno.nombre = "Antonio";
  22.  
  23.     fwrite( &alumno, sizeof( __ALUMNO__ ), sizeof (alum)/8, fp );
  24.    
  25.     alumno.clave = 123;
  26.     alumno.nombre = "Luis";
  27.  
  28.     fwrite( &alumno, sizeof( __ALUMNO__ ), sizeof (alum)/8, fp );  
  29.    
  30.         alumno.clave = 789;
  31.     alumno.nombre = "Anuska";
  32.  
  33.     fwrite( &alumno, sizeof( __ALUMNO__ ), sizeof (alum)/8, fp );
  34.    
  35.    
  36.     fclose( fp );
  37. }
  38.  
  39.  
  40. int main () {
  41.   FILE * pFile;
  42.   long lSize;
  43.   __ALUMNO__ * buffer, *buffer0;
  44.   size_t result;
  45.  
  46.     escribe();
  47.  
  48.   pFile = fopen ( "alumnos.txt" , "r" );
  49.   if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
  50.  
  51.   // obtain file size:
  52.   fseek (pFile , 0 , SEEK_END);
  53.   lSize = ftell (pFile);
  54.   rewind (pFile);
  55.  
  56.   // allocate memory to contain the whole file:
  57.   buffer = (__ALUMNO__*) malloc (sizeof(__ALUMNO__)*lSize);
  58.   if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
  59.  
  60.  
  61.   // copy the file into the buffer:
  62.  
  63.   result = fread (buffer,sizeof (alum)/8,lSize,pFile);
  64.   if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
  65.  
  66.  
  67.     printf (" %d %s \n",(buffer)->clave,((buffer)->nombre).c_str());
  68.  
  69.   /* the whole file is now loaded in the memory buffer. */
  70.  
  71.   // terminate
  72.   fclose (pFile);
  73.  // printf (" %d %s \n",(buffer)->clave,((buffer)->nombre).c_str());
  74.  
  75.   free (buffer);
  76.   return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement