FileIO.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include "FileIO.h"
  4. // Function : read all data from file to a buffer.
  5. // Note : The buffer is malloc in this function and need to be free outside by user !
  6. // Parameter :
  7. // size_t *p_len : getting the data length, i.e. the file length.
  8. // const char *filename : file name
  9. // Return :
  10. // non-NULL pointer : success. Return the data buffer pointer. The data length will be on *p_len
  11. // NULL : failed
  12. uint8_t *loadFromFile (size_t *p_len, const char *filename) {
  13. size_t rlen = 0;
  14. FILE *fp = NULL;
  15. uint8_t *p_buf = NULL;
  16. *p_len = 0;
  17. fp = fopen(filename, "rb");
  18. if (fp == NULL)
  19. return NULL;
  20. if (0 != fseek(fp, 0, SEEK_END)) {
  21. fclose(fp);
  22. return NULL;
  23. }
  24. *p_len = ftell(fp); // get file data length
  25. if (0 != fseek(fp, 0, SEEK_SET)) {
  26. fclose(fp);
  27. return NULL;
  28. }
  29. if (*p_len == 0) { // special case : file length = 0 (empty file)
  30. fclose(fp);
  31. p_buf = (uint8_t*)malloc(1); // malloc a 1-byte buffer
  32. return p_buf; // directly return it without filling any data
  33. }
  34. p_buf = (uint8_t*)malloc((*p_len));
  35. if (p_buf == NULL) {
  36. fclose(fp);
  37. return NULL;
  38. }
  39. rlen = fread(p_buf, sizeof(uint8_t), (*p_len), fp);
  40. fclose(fp);
  41. if (rlen != (*p_len)) { // actual readed length is not equal to expected readed length
  42. free(p_buf);
  43. return NULL;
  44. }
  45. return p_buf;
  46. }
  47. // Function : write data from buffer to a file.
  48. // Parameter :
  49. // const uint8_t *p_buf : data buffer pointer
  50. // size_t len : data length
  51. // const char *filename : file name
  52. // Return :
  53. // 0 : failed
  54. // 1 : success
  55. int saveToFile (const uint8_t *p_buf, size_t len, const char *filename) {
  56. size_t wlen = 0;
  57. FILE *fp;
  58. fp = fopen(filename, "wb");
  59. if (fp == NULL)
  60. return 1;
  61. if (len > 0)
  62. wlen = fwrite(p_buf, sizeof(uint8_t), len, fp);
  63. fclose(fp);
  64. if (wlen != len)
  65. return 1;
  66. return 0;
  67. }