is_writable.h 1.3 KB

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