Advertisement
dalvorsn

Untitled

Apr 21st, 2012
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.95 KB | None | 0 0
  1. /* fread example: read a complete file */
  2. #include "iostream"
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5.  
  6. int main () {
  7.   FILE * pFile;
  8.   long lSize;
  9.   char * buffer;
  10.   size_t result;
  11.  
  12.   pFile = fopen ( "new.txt" , "rb" );
  13.   if (pFile==NULL) {fputs ("File error\n",stderr); exit (1);}
  14.   std::cout << pFile << std::endl;
  15.   // obtain file size:
  16.   fseek (pFile , 0 , SEEK_END);
  17.   lSize = ftell (pFile);
  18.   rewind (pFile);
  19.  
  20.   // allocate memory to contain the whole file:
  21.   buffer = (char*) malloc (sizeof(char)*lSize);
  22.   if (buffer == NULL) {fputs ("Memory error\n",stderr); exit (2);}
  23.  
  24.   // copy the file into the buffer:
  25.   result = fread (buffer,1,lSize,pFile);
  26.   if (result != lSize) {fputs ("Reading error\n",stderr); exit (3);}
  27.  
  28.   /* the whole file is now loaded in the memory buffer. */
  29.   std::cout << pFile << "\n" << lSize << "\n" << buffer << std::endl;
  30.   // terminate
  31.   fclose (pFile);
  32.   free (buffer);
  33.   system("pause");
  34.   return 0;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement