load_file.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /* libs/cutils/load_file.c
  2. **
  3. ** Copyright 2006, The Android Open Source Project
  4. **
  5. ** Licensed under the Apache License, Version 2.0 (the "License");
  6. ** you may not use this file except in compliance with the License.
  7. ** You may obtain a copy of the License at
  8. **
  9. ** http://www.apache.org/licenses/LICENSE-2.0
  10. **
  11. ** Unless required by applicable law or agreed to in writing, software
  12. ** distributed under the License is distributed on an "AS IS" BASIS,
  13. ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. ** See the License for the specific language governing permissions and
  15. ** limitations under the License.
  16. */
  17. #include <cutils/misc.h>
  18. #include <stdlib.h>
  19. #include <unistd.h>
  20. #include <fcntl.h>
  21. void *load_file(const char *fn, unsigned *_sz)
  22. {
  23. char *data;
  24. int sz;
  25. int fd;
  26. data = 0;
  27. fd = open(fn, O_RDONLY);
  28. if(fd < 0) return 0;
  29. sz = lseek(fd, 0, SEEK_END);
  30. if(sz < 0) goto oops;
  31. if(lseek(fd, 0, SEEK_SET) != 0) goto oops;
  32. data = (char*) malloc(sz + 1);
  33. if(data == 0) goto oops;
  34. if(read(fd, data, sz) != sz) goto oops;
  35. close(fd);
  36. data[sz] = 0;
  37. if(_sz) *_sz = sz;
  38. return data;
  39. oops:
  40. close(fd);
  41. if(data != 0) free(data);
  42. return 0;
  43. }