is_writable.h 1015 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. inline bool is_writable(const char * filename);
  12. }
  13. // Implementation
  14. #include <sys/stat.h>
  15. #include <unistd.h>
  16. inline bool igl::is_writable(const char* filename)
  17. {
  18. // Check if file already exists
  19. struct stat status;
  20. if(stat(filename,&status)!=0)
  21. {
  22. return false;
  23. }
  24. // Get current users uid and gid
  25. uid_t this_uid = getuid();
  26. gid_t this_gid = getgid();
  27. // Dealing with owner
  28. if( this_uid == status.st_uid )
  29. {
  30. return S_IWUSR & status.st_mode;
  31. }
  32. // Dealing with group member
  33. if( this_gid == status.st_gid )
  34. {
  35. return S_IWGRP & status.st_mode;
  36. }
  37. // Dealing with other
  38. return S_IWOTH & status.st_mode;
  39. }
  40. #endif