Posted By

Zufolek on 05/16/09


Tagged

file save load memory


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

skammer


load or save a chunk of memory to/from file


 / Published in: C
 

loadfile(filename); returns NULL on fail or a pointer that should be free()d when no longer needed.

savefile(filename,data,dataSize); returns 0 on fail or 1 on success.

  1. void*loadfile(const char*const s){
  2. FILE*f=fopen(s,"rb");
  3. if(f){
  4. fseek(f,0,SEEK_END);
  5. {
  6. const int ml=ftell(f);
  7. if(ml){
  8. char*m=malloc(ml);
  9. if(m){
  10. rewind(f);
  11. fread(m,1,ml,f);
  12. fclose(f);
  13. return m;
  14. }
  15. }
  16. }
  17. }
  18. return 0;
  19. }
  20.  
  21.  
  22. int savefile(const char*const s,const void*const m,const int ml){
  23. FILE*f=fopen(s,"wb");
  24. if(f){
  25. int ok=fwrite(m,1,ml,f)==ml;
  26. fclose(f);
  27. return ok;
  28. }
  29. return 0;
  30. }

Report this snippet  

You need to login to post a comment.