Angel David Yaguana Hernandez
/
CPP_fread
fread, descripcion y ejemplo
main.cpp
- Committer:
- sherckuith
- Date:
- 2012-04-03
- Revision:
- 0:2191a269e668
File content as of revision 0:2191a269e668:
#include "mbed.h" #include "SDFileSystem.h" Serial pc(USBTX, USBRX); LocalFileSystem chip("uc"); SDFileSystem sd(p5, p6, p7, p8,"sd"); int main () { pc.baud(115200); FILE * pFile; long lSize; char * buffer; size_t result; pFile = fopen ( "/sd/Justin.mp3","r"); if (pFile==NULL) { fputs ("File error",stderr); exit (1); } // obtain file size: fseek (pFile , 0 , SEEK_END); lSize = ftell (pFile); rewind (pFile); pc.printf("Tamanio: %d\n",lSize); wait(3); // allocate memory to contain the whole file: buffer = (char*) malloc (sizeof(char)*lSize); if (buffer == NULL) { fputs ("Memory error",stderr); exit (2); } // copy the file into the buffer: result = fread (buffer,1,lSize,pFile); if (result != lSize) { fputs ("Reading error",stderr); exit (3); } pc.printf("%s",buffer); /* the whole file is now loaded in the memory buffer. */ fclose (pFile); free (buffer); return 0; } //This code loads myfile.bin into a dynamically allocated memory buffer, //which can be used to manipulate the content of a file as an array. /* function: fread Library: <cstdio> size_t fread ( void * ptr, size_t size, size_t count, FILE * stream ); Read block of data from stream Reads an array of count elements, each one with a size of size bytes, from the stream and stores them in the block of memory specified by ptr. The postion indicator of the stream is advanced by the total amount of bytes read. The total amount of bytes read if successful is (size * count). Parameters ptr Pointer to a block of memory with a minimum size of (size*count) bytes. size Size in bytes of each element to be read. count Number of elements, each one with a size of size bytes. stream Pointer to a FILE object that specifies an input stream. Return Value The total number of elements successfully read is returned as a size_t object, which is an integral data type. If this number differs from the count parameter, either an error occured or the End Of File was reached. You can use either ferror or feof to check whether an error happened or the End-of-File was reached. */