在 Go 中验证文件的可执行性
在 Go 中,您可以通过检查文件模式(特别是权限位)来确定文件是否可执行。以下是如何构造一个函数来执行此检查:
<code class="go">import ( "os" ) func IsExecutable(mode os.FileMode) bool { return mode&0111 != 0 }</code>
此函数使用按位与运算符 (&) 从文件模式中提取最低 9 个权限位(0777 八进制位掩码)。位掩码 0111 允许我们验证文件的任何权限位是否设置为执行。如果设置了任何位,该函数将返回 true。
测试用例:
考虑以下测试用例:
<code class="sh">#!/usr/bin/env bash ... # create test directory and files ... # set executable permission on quux.sh chmod +x test/foo/bar/quux.sh ...</code>
以及相应的Go 代码:
<code class="go">import ( "os" "path/filepath" "fmt" ) func main() { filepath.Walk("test", func(path string, info os.FileInfo, err error) error { if err != nil || info.IsDir() { return err } fmt.Printf("%v %v", path, IsExecutable(info.Mode())) } }</code>
运行此代码应打印:
test/foo/bar/baz.txt false test/foo/bar/quux.sh true
这确认了 baz.txt 不可执行,而 quux.sh 则如测试用例所预期的那样。
Windows 兼容性
提供的解决方案特定于 Unix 系统,包括 Linux 和 macOS。对于 Windows,您可以使用 os.可执行函数来确定文件是否可执行。但值得注意的是,os.Executable 仅指示该文件是否具有“.exe”扩展名,而不是其实际的可执行性。
以上是Go中如何判断一个文件是否可执行?的详细内容。更多信息请关注PHP中文网其他相关文章!