开发者

How does _stat() under Windows exactly work

开发者 https://www.devze.com 2023-03-07 22:49 出处:网络
In my code I try to get the permissions for a file with _stat(). Currently I want to run it under Windows. The method is as follows:

In my code I try to get the permissions for a file with _stat(). Currently I want to run it under Windows. The method is as follows:

bool CFile::Private::checkPermissions(std::string sFilename, CFile::EOpenmode iOpenmode)
{
  std::string sErrMsg = "";
  bool bResult = true;
  struct _stat buf;
  int iResult = 0;

  // Get data associated with "crt_stat.c": 
  iResult = _stat( sFilename.c_str(), &buf );

  // Check if statistics are valid: 
  if( iResult != 0 )
  {
    switch (errno)
    {
开发者_运维问答      case ENOENT:
        sErrMsg = "File: " + sFilename + " not found.";
        break;
      case EINVAL:
        sErrMsg = "Invalid parameter to _stat(filename, &buf).";
        break;
      default:
        /* Should never be reached. */
        sErrMsg = "Unexpected error in _stat(filename, &buf).";
    }
    throw std::runtime_error(sErrMsg);
  }
  else
  {
    if((iOpenmode & CFile::Read) && (!(buf.st_mode & S_IREAD)))
    {
      bResult = false;
    }
    if((iOpenmode & CFile::Write) && (!(buf.st_mode & S_IWRITE)))
    {
      bResult = false;
    }
  }
  return bResult;
}

The only way to get 'false' for permission is to set the file's attribute 'read only'. Instead of this, set the security properties of the user (reject writing and reading) will get 'true' for checkPermissions(...). How to check both, the attributes and the user permissions for Windows?

Rumo


_stat is a function that is not native to Windows. It's a helper function to ease the porting of UNIX programs to Windows. But the UNIX file model just doesn't apply to Windows, so not all fields make sense. For instance, Windows has real ACL's, not rwx bits. There's just no way to fit all the ACL information in st_mode.

If you want to test ACL permissions, the proper way is to just try: call CreateFile() and check GetLastError(). Trying to get file permissions up front is not reliable as they can change at any time.


If we're talking about the same _stat() it's pretty clear from this MSDN article exactly what it does. Basically, you supply it a path to a file in question and a pointer to a _stat struct and it will dump the permissions to the struct if it returns 0.

The example C++ code in the article is pretty good.

As for testing user permissions, IsUserAnAdmin() does the job pretty well. You may be able to use this MSDN article for a different approach.

I hope this helps!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号