FileIO.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. //
  2. // Created by miti on 21/07/19.
  3. //
  4. #include "UntrustedInclude/FileIO.h"
  5. namespace FileIO {
  6. /*
  7. FILE* file;
  8. file = fopen(filename, "w");
  9. if(file == NULL)
  10. return errno;
  11. fd = fileno(file);
  12. if(fd == -1)
  13. return errno;
  14. */
  15. int write_to_fd(int fd, uint8_t* msg, size_t* expected_msg_length)
  16. {
  17. ssize_t bytes_written;
  18. lseek(fd, 0, SEEK_SET);
  19. bytes_written = write(fd, msg, *expected_msg_length);
  20. if(bytes_written == -1)
  21. return -1;
  22. fsync(fd);
  23. *expected_msg_length = bytes_written;
  24. return 0;
  25. }
  26. int read_from_fd(int fd, uint8_t* msg, size_t* expected_msg_length)
  27. {
  28. ssize_t bytes_read;
  29. lseek(fd, 0, SEEK_SET);
  30. bytes_read = read(fd, msg, *expected_msg_length);
  31. if(bytes_read == -1)
  32. return -1;
  33. *expected_msg_length = bytes_read;
  34. return 0;
  35. }
  36. size_t check_if_file_exists_return_size(char* filename, int* fd_ptr)
  37. {
  38. int fd, ret_status;
  39. FILE* file;
  40. struct stat st;
  41. file = fopen(filename, "r");
  42. if(file == NULL)
  43. return 0;
  44. fd = fileno(file);
  45. if(fd == -1)
  46. return 0;
  47. printf("\nSuccessfully opened a file to seal the signing key pair for the client.\n");
  48. fflush(stdout);
  49. ret_status = fstat(fd, &st);
  50. if(ret_status != 0)
  51. {
  52. perror("error in finding the file size. - ");
  53. fflush(stderr);
  54. return 0;
  55. }
  56. *fd_ptr = fd;
  57. return st.st_size;
  58. }
  59. };