common.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include <stdbool.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. char *loadfile(const char *fname, unsigned int *s) {
  6. FILE *f = fopen(fname, "rb");
  7. unsigned int size = 0; // number of elements to buffer;
  8. unsigned int rcnt = 0; // number of char's read by fread(...)
  9. if (f == NULL) {
  10. perror("Error 1: ");
  11. return NULL;
  12. }
  13. // this method of determining file size works up to 2 GB.
  14. fseek(f, 0, SEEK_END);
  15. size = ftell(f);
  16. rewind(f);
  17. char *buf = (char*)malloc(sizeof(char) * size);
  18. if (buf == NULL) {
  19. perror("Error 2: ");
  20. free(buf);
  21. return NULL;
  22. }
  23. rcnt = fread(buf, sizeof(char), size, f);
  24. if (rcnt < size) {
  25. perror("Error 3: ");
  26. free(buf);
  27. return NULL;
  28. }
  29. fclose(f);
  30. *s = rcnt;
  31. return buf;
  32. }
  33. void write(const char *filename,
  34. const char* t,
  35. unsigned int size) {
  36. if (filename == NULL) {
  37. return;
  38. }
  39. unsigned int written = 0;
  40. FILE *out = fopen(filename, "wb");
  41. if (out != NULL) {
  42. written = fwrite(t, sizeof(unsigned char), size, out);
  43. fclose(out);
  44. if (written == 0) {
  45. perror("write error");
  46. exit(4);
  47. }
  48. }
  49. }
  50. void append(const char *filename, const char *t, unsigned size) {
  51. if (filename == NULL) {
  52. return;
  53. }
  54. unsigned int written = 0;
  55. FILE *out = fopen(filename, "ab");
  56. if (out != NULL) {
  57. written = fwrite(t, sizeof(unsigned char), size, out);
  58. fclose(out);
  59. if (written == 0) {
  60. perror("write error");
  61. exit(4);
  62. }
  63. }
  64. }