Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //compilacion g++ -std=c++11 -o NombreEjecutable NombreFuente.cpp
- /* fread example: read an entire file */
- #include <stdio.h>
- #include <stdlib.h>
- #include <iostream>
- using namespace std;
- typedef struct alum {int clave;string nombre;}__ALUMNO__;
- void escribe()
- {
- __ALUMNO__ alumno;
- //FILE* fp = fopen( "alumnos.txt", "wb+" );
- FILE* fp = fopen( "alumnos.txt", "a+" );
- alumno.clave = 666;
- alumno.nombre = "Antonio";
- fwrite( &alumno, sizeof( __ALUMNO__ ), sizeof (alum)/8, fp );
- alumno.clave = 123;
- alumno.nombre = "Luis";
- fwrite( &alumno, sizeof( __ALUMNO__ ), sizeof (alum)/8, fp );
- alumno.clave = 789;
- alumno.nombre = "Anuska";
- fwrite( &alumno, sizeof( __ALUMNO__ ), sizeof (alum)/8, fp );
- fclose( fp );
- }
- int main () {
- FILE * pFile;
- long lSize;
- __ALUMNO__ * buffer, *buffer0;
- size_t result;
- escribe();
- pFile = fopen ( "alumnos.txt" , "r" );
- if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
- // obtain file size:
- fseek (pFile , 0 , SEEK_END);
- lSize = ftell (pFile);
- rewind (pFile);
- // allocate memory to contain the whole file:
- buffer = (__ALUMNO__*) malloc (sizeof(__ALUMNO__)*lSize);
- if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
- // copy the file into the buffer:
- result = fread (buffer,sizeof (alum)/8,lSize,pFile);
- if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
- printf (" %d %s \n",(buffer)->clave,((buffer)->nombre).c_str());
- /* the whole file is now loaded in the memory buffer. */
- // terminate
- fclose (pFile);
- // printf (" %d %s \n",(buffer)->clave,((buffer)->nombre).c_str());
- free (buffer);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement