Advertisement
Guest User

Untitled

a guest
Oct 29th, 2011
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.78 KB | None | 0 0
  1. char* filetobuf(char *file) //will reac a file into an allocated char pointer buffer
  2. {  
  3.     FILE *fptr;
  4.     long length;
  5.     char *buf;
  6.     //opening the file
  7.     fptr = fopen(file, "rb");
  8.     struct stat statbuf;
  9.  
  10.     if(!fptr)
  11.     {
  12.         fprintf(stderr, "failed to open %s\n", file);
  13.         return NULL;
  14.     }
  15.     //fseek(fptr,0,SEEK_END); //go to the end of the file
  16.     //length = ftell(fptr); //count bytes in "fptr" file
  17.     if(fstat(file,&statbuf) < 0)    
  18.             return 1;
  19.     length = statbuf.st_size;
  20.     buf = malloc(length+1); //allocate a buffer for all the file and +1 for the null terminator
  21.     //fseek(fptr, 0, SEEK_SET); //SEEK_SET = Begging of file >> go to hte start of the file
  22.     fread(fptr, 1, length, buf);
  23.     fclose(fptr); //close the file
  24.     free(fptr);
  25.  
  26.     buf[length] = 0; //null terminator
  27.     return buf;
  28. }
  29.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement