is_readable
is_readable(string $filename): bool
文件/目录是否存在且可读(按真实 UID/GID 检查,结果有 stat 缓存);同族还有 is_writable/is_executable。
C C23
#include <stdio.h>
#include <unistd.h>
int main(void) {
/* access(R_OK) 按真实 UID(而非有效 UID)检查可读性——与 PHP
is_readable 手册写明的语义一致(SUID 程序要注意) */
const char *path = "/tmp/a18read_c.txt";
FILE *fp = fopen(path, "w");
fputs("data", fp);
fclose(fp);
printf("%d\n", access(path, R_OK) == 0);
printf("%d\n", access("/tmp/a18read_c.nonexistent", R_OK) == 0);
unlink(path);
return 0;
}
1 0
C++ C++26
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <iostream>
int main() {
// C++ 没有 access(2):可移植惯用法是用 ifstream 试开
const std::string path =
(std::filesystem::temp_directory_path() / "a18read_cpp.txt").string();
{
std::ofstream out(path);
out << "data";
}
std::ifstream in(path);
std::cout << std::boolalpha << in.is_open() << "\n";
in.close();
std::ifstream missing(path + ".nonexistent");
std::cout << missing.is_open() << "\n";
std::remove(path.c_str());
return 0;
}
true false
C# v11.0.100
// FileInfo.Attributes:Windows 用只读标志建模「可写性」,所以单纯的
// 「可读」检查退化为存在性(拒绝访问要 try/开文件才知道)
string path = Path.Combine(Path.GetTempPath(), "a18read_cs.txt");
File.WriteAllText(path, "data");
var info = new FileInfo(path);
Console.WriteLine(info.Exists);
Console.WriteLine(info.Attributes.HasFlag(FileAttributes.ReadOnly));
Console.WriteLine(new FileInfo(path + ".nonexistent").Exists);
File.Delete(path);
True False False
Go v1.27.4
package main
import (
"fmt"
"os"
)
func main() {
// Go 标准库没有 access(2):惯用法是真实试开
f, err := os.CreateTemp("", "a18read")
if err != nil {
panic(err)
}
name := f.Name()
f.Close()
fh, err := os.Open(name)
if err != nil {
fmt.Println("not readable:", err)
} else {
fmt.Println("readable")
fh.Close()
}
_, err = os.Open(name + ".nonexistent")
fmt.Println(err != nil)
}
readable true
Java v27.0.1
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws IOException {
// File.canRead() 检查可读性(JVM 映射到 access(R_OK))
Path p = Files.createTempFile("a18read", ".txt");
System.out.println(p.toFile().canRead());
System.out.println(p.resolveSibling(p.getFileName() + ".nonexistent").toFile().canRead());
Files.delete(p);
}
}
true false
JavaScript v26.13.1
// fs.accessSync(path, R_OK):通过返回 undefined,失败抛异常
const fs = require("fs");
const path = require("os").tmpdir() + "/a18_readable.txt";
fs.writeFileSync(path, "data");
console.log(fs.accessSync(path, fs.constants.R_OK) === undefined);
try {
fs.accessSync(path + ".nonexistent", fs.constants.R_OK);
console.log("readable");
} catch {
console.log(false);
}
fs.unlinkSync(path);
// Promise 形态:fs.promises.access 通过则 resolve,失败则 reject
fs.promises.access(path + ".nonexistent", fs.constants.R_OK).then(
() => console.log("readable"),
() => console.log("rejected")
);
true false rejected
PHP v8.6.0
// is_readable 检查存在+可读(按真实 UID/GID,见手册)
$f = tempnam(sys_get_temp_dir(), 'rd');
var_dump(is_readable($f));
var_dump(is_readable($f . '.nonexistent'));
// 目录也返回 true——用 is_dir 区分
var_dump(is_readable(sys_get_temp_dir()));
unlink($f);
bool(true) bool(false) bool(true)
Python v3.15.2
import os
import tempfile
# os.access(R_OK):可读性检查(真实 uid 语义,同 C access(2))
path = os.path.join(tempfile.gettempdir(), "a18_readable.txt")
with open(path, "w") as fh:
fh.write("data")
print(os.access(path, os.R_OK))
print(os.access(path + ".nonexistent", os.R_OK))
print(os.access(tempfile.gettempdir(), os.R_OK))
os.remove(path)
True False True
Rust v1.99.1
fn main() {
// metadata().permissions() 暴露 mode 位:检查 POSIX 读位
// (仅 Unix;Windows 权限是另一套模型)
use std::os::unix::fs::PermissionsExt;
let path = std::env::temp_dir().join("a18read_rs.txt");
std::fs::write(&path, "data").unwrap();
let mode = std::fs::metadata(&path).unwrap().permissions().mode();
println!("{}", mode & 0o444 != 0);
println!("{}", std::fs::metadata(path.with_extension("nonexistent")).is_err());
std::fs::remove_file(&path).unwrap();
}
true true
TypeScript v26.13.1
// fs.accessSync(path, R_OK):通过返回 undefined,失败抛异常
import * as fs from "fs";
import * as os from "os";
const path = os.tmpdir() + "/a18_readable.txt";
fs.writeFileSync(path, "data");
console.log(fs.accessSync(path, fs.constants.R_OK) === undefined);
try {
fs.accessSync(path + ".nonexistent", fs.constants.R_OK);
console.log("readable");
} catch {
console.log(false);
}
fs.unlinkSync(path);
fs.promises.access(path + ".nonexistent", fs.constants.R_OK).then(
() => console.log("readable"),
() => console.log("rejected")
);
true false rejected
语言差异说明
C:access(path, R_OK)——检查用真实 UID 而非有效 UID(手册安全教学点:SUID 程序拿 access 判「能不能以当前权限读」会误判——TOCTOU 漏洞温床,推荐直接 open 试错);同族 W_OK/X_OK/F_OK。
C++:没有 access(2) 绑定——可移植惯用法 ifstream 试开 is_open();C++17 filesystem 有 permissions()/status() 但「当前用户能否读」仍要试开。
C#:FileInfo.Attributes 只有只读标志(Windows 语义:读权限建模为「不可写」)——单纯「可读」检查退化为存在性,拒绝访问要 try/开文件才知道;Unix 上 .NET 映射 mode 位但语义仍简化。
Go:标准库没有 access(2)——惯用法 os.Open 真实试开(错误分支顺便告诉你为什么不可读);golang.org/x/sys/unix.Access 有真 access(需要外部依赖)。
Java:File.canRead()——JVM 映射到 OS 的 access(R_OK);Files.isReadable(Path) 是 NIO 版;Java 没有「真实 vs 有效 UID」的暴露——运行身份就是 JVM 进程身份。
JavaScript:fs.accessSync(path, fs.constants.R_OK) 通过返回 undefined、失败抛异常(「无异常即通过」的异常式语义与 PHP 布尔式相反);Promise 形态 fs.promises.access resolve/reject 同理;同族 W_OK/X_OK/F_OK。
PHP:is_readable 按真实 UID/GID 检查(手册明示——与 C access 同语义,SUID/CLI setuid 场景注意);目录也返回 true(用 is_dir 区分);结果受 stat 缓存影响(clearstatcache 清理);同族 is_writable/is_executable;网页场景 PHP 常以 Web 服务器用户(如 nobody)访问文件,手册提醒这也是可读性判定的实际身份。
Python:os.access(path, os.R_OK)——真实 uid 语义同 C;os.path.isfile/os.stat 配合可用;注意 os.access 对 root 恒真(root 可读一切,与 PHP/JS 同坑)。
Rust:metadata().permissions() 暴露 POSIX mode 位(PermissionsExt::mode())——判「当前用户可读」要按 uid/位运算自算;跨平台要用 #[cfg(unix)](Windows 权限模型不同)。
TypeScript:同 JavaScript(accessSync/promises.access + R_OK 常量)。