load or save a chunk of memory to/from file


/ Published in: C
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.