os.Stat: 权限被拒绝 => 错误(syscall.Errno) EACCES (13)

huangapple go评论69阅读模式
英文:

os.Stat: permission denied => error(syscall.Errno) EACCES (13)

问题

我正在创建一个单元测试中的目录,代码如下:

// 将要创建的目录,位于单元测试可执行文件旁边。
const DirName string = "test-files"

创建目录:

    // 如果目录不存在,则创建目录。
	err := os.MkdirAll(DirName, os.ModeDir)
	if err != nil {
		return err
	}

	// 组合一个样本文件路径,以双重检查其是否存在。
	pth := DirName + string(os.PathSeparator) + "samplefile.txt";


	exists, err := doesExist(pth)
	if err != nil {
		return err
	}

检查文件是否存在:


// 文件是否存在?
func doesExist(pth string) (bool, error) {

	// 检查文件是否存在
	// https://stackoverflow.com/a/10510718/3405291
	if _, err := os.Stat(pth); err != nil {
		if os.IsNotExist(err) {
			return false, nil
		} else {
			return true, err
		}
	}

	// 上述条件被跳过,
	// 因此文件存在。
	return true, nil
}

上述代码返回以下错误:

os.Stat: permission denied

error(syscall.Errno) EACCES (13)

我可以双重检查目录是否实际创建。但是权限是 d---------

> ls -lh
d--------- 2 m3 users    6 Dec 23 20:30 test-files

如何以适当的权限创建目录?

英文:

I'm creating a directory inside a unit test like this:

// The directory which is going to be created next to unit test executable.
const DirName string = "test-files"

Creating directory:

    // Create the directory if doesn't already exist.
	err := os.MkdirAll(DirName, os.ModeDir)
	if err != nil {
		return err
	}

	// Compose a sample file path to double-check its existence.
	pth := DirName + string(os.PathSeparator) + "samplefile.txt"


	exists, err := doesExist(pth)
	if err != nil {
		return err
	}

And checking file existence:


// Does file exist?
func doesExist(pth string) (bool, error) {

	// Check file existence
	// https://stackoverflow.com/a/10510718/3405291
	if _, err := os.Stat(pth); err != nil {
		if os.IsNotExist(err) {
			return false, nil
		} else {
			return true, err
		}
	}

	// Above conditions are skipped,
	// therefore file exists.
	return true, nil
}

The above code returns this error:

> os.Stat: permission denied

> error(syscall.Errno) EACCES (13)

I can double-check that the directory is actually created. But the permissions are d---------:

> ls -lh
d--------- 2 m3 users    6 Dec 23 20:30 test-files

How can I create the directory with the appropriate permissions?

答案1

得分: 2

你滥用了os.ModeDir常量。它被设计为位掩码,用于检查文件的模式+权限位(例如通过os.(*File).Stat返回)是否表示它是一个目录。

创建目录的默认权限模式位是0777,但它们受到umask的影响。

英文:

You're abusing the os.ModeDir constant. It's invented to serve as the bit mask to check whether the file's mode+permissions bits (returned by, say, os.(*File).Stat indicate it's a directory.

The default permission mode bits to create a directory are 0777 but they are subject to umask.

huangapple
  • 本文由 发表于 2021年12月24日 01:09:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/70465320.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定