is_readable.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #ifndef IGL_IS_READABLE_H
  2. #define IGL_IS_READABLE_H
  3. namespace igl
  4. {
  5. // Check if a file is reabable like PHP's is_readable function:
  6. // http://www.php.net/manual/en/function.is-readable.php
  7. // Input:
  8. // filename path to file
  9. // Returns true if file exists and is readable and false if file doesn't
  10. // exist or *is not readable*
  11. //
  12. // Note: Windows version will not check user or group ids
  13. inline bool is_readable(const char * filename);
  14. }
  15. // Implementation
  16. #ifdef _WIN32
  17. # include <cstdio>
  18. inline bool igl::is_readable(const char* filename)
  19. {
  20. FILE * f = fopen(filename,"r");
  21. if(f == NULL)
  22. {
  23. return false;
  24. }
  25. fclose(f);
  26. return true;
  27. }
  28. #else
  29. # include <sys/stat.h>
  30. # include <unistd.h>
  31. inline bool igl::is_readable(const char* filename)
  32. {
  33. // Check if file already exists
  34. struct stat status;
  35. if(stat(filename,&status)!=0)
  36. {
  37. return false;
  38. }
  39. // Get current users uid and gid
  40. uid_t this_uid = getuid();
  41. gid_t this_gid = getgid();
  42. // Dealing with owner
  43. if( this_uid == status.st_uid )
  44. {
  45. return S_IRUSR & status.st_mode;
  46. }
  47. // Dealing with group member
  48. if( this_gid == status.st_gid )
  49. {
  50. return S_IRGRP & status.st_mode;
  51. }
  52. // Dealing with other
  53. return S_IROTH & status.st_mode;
  54. }
  55. #endif
  56. #endif