Conceptcore
File metadata
Also called file attributes, stat, lstat, inode attributes, extended attributes, xattr, file status.
File metadata is the data about a file that is not in its bytes: the type, the size, the owner, the permissions, the link count and the times. A stat call reads it, with or without a link.
- Applies to
- core-languages
Idea
A file has its bytes, and it also has data about the bytes. The file system knows the type of the file, its size, its owner, its permissions, the number of names that it has, and the times of its last changes. This data is the metadata of the file. A program does not read it from the file. It asks the file system with one call, which POSIX names stat.
import os
import stat
from pathlib import Path
os.mkdir("box")
os.chdir("box")
Path("data.txt").write_text("hello", encoding="utf-8")
os.chmod("data.txt", 0o640)
os.utime("data.txt", (1700000000, 1700000000))
os.link("data.txt", "second-name.txt")
os.symlink("data.txt", "link")
st = os.stat("data.txt")
print("type:", "regular file" if stat.S_ISREG(st.st_mode) else "other")
print("size:", st.st_size)
print("permissions:", stat.filemode(st.st_mode)[1:])
print("links:", st.st_nlink)
print("owner is me:", st.st_uid == os.getuid())
print("mtime:", int(st.st_mtime))
print("ctime is later than mtime:", st.st_ctime > st.st_mtime)
# The link has metadata of its own. lstat reads it, stat follows the link.
lst = os.lstat("link")
print("link:", "symbolic link" if stat.S_ISLNK(lst.st_mode) else "other",
"of size", lst.st_size)
print("stat of the link is the file:", os.stat("link") == st)
type: regular file
size: 5
permissions: rw-r-----
links: 2
owner is me: True
mtime: 1700000000
ctime is later than mtime: True
link: symbolic link of size 8
stat of the link is the file: True
The program makes a file of 5 bytes, sets its permissions and its modification time, and gives it a second name and a symbolic link. One os.stat call returns all of the fields. The modification time is the value that the program set, but the change time is later, because the calls to chmod, utime and link changed the metadata. The link is a file of its own: os.lstat shows a symbolic link whose size is the length of the path data.txt, and os.stat follows the link to the file.
How it works
The stat structure. POSIX defines struct stat in <sys/stat.h>, and the structure "shall include at least the following members"1. They are the device ID and the file serial number, which together identify the file, the mode, the link count, the owner and the group, the size, three times and the block counts1. The link count is the "Number of hard links to the file"1. The size is "For regular files, the file size in bytes"1. The three times are the "Last data access timestamp", the "Last data modification timestamp" and the "Last file status change timestamp"1. These fields come from the Unix i-node. The paper of 1974 says that the i-node "contains the description of the file", which includes "the user and group-ID of its owner", "its protection bits", "its size" and "the number of links to the file"6.
The mode. One number, st_mode, holds two things. Python describes it as the "File mode: file type and file mode bits (permissions)"7. The type bits tell a regular file from a directory, a symbolic link, a FIFO, a socket or a device, and macros such as S_ISREG and S_ISLNK test them. The low bits are the permissions of the owner, the group and the others. See File permissions.
The times. The modification time changes when the data changes. The change time is not a creation time. Linux says that it "is changed by writing or by setting inode information (i.e., owner, group, link count, mode, etc.)"3. A creation time, or birth time, is not in the stat structure of POSIX. On Linux, it comes only from statx, and "The btime timestamp was not historically present on UNIX systems and is not currently supported by most Linux filesystems"3. See Get the modification time of a file.
Follow the link or not. A symbolic link is a file that holds a path, so it has metadata of its own. POSIX has two calls. For lstat, "In that case lstat() shall return information about the link, while stat() shall return information about the file the link references"2. For a link, the size is "the length in bytes of the pathname contained in the symbolic link"1. Each language has the two forms:
- Python has
os.statandos.lstat, and most calls takefollow_symlinks7. - Node.js has
lstat, where "the link itself is stat-ed, not the file that it refers to"8. - In Java, "By default, symbolic links are followed", and
NOFOLLOW_LINKSchanges this12. - Go's
os.Lstat"makes no attempt to follow the link"15. - Rust has
fs::metadataandfs::symlink_metadata16. - C++ has
statusandsymlink_status, which works "as if the POSIX lstat is used (symlinks are not followed)"18.
Extended attributes. The fixed fields are not enough for some programs. "Extended attributes are name:value pairs associated permanently with files and directories, similar to the environment strings associated with a process"5. On Linux, the name has a namespace, such as user.mime_type, trusted.md5sum, system.posix_acl_access or security.selinux5. The file system keeps them, but they have limits: "The VFS-imposed limits on attribute names and values are 255 bytes and 64 kB, respectively"5. Python has os.getxattr, os.setxattr and os.listxattr7. In Java, "User-defined file attributes are used to store metadata with a file that is not meaningful to the file system"11.
Windows. Windows keeps a different set. GetFileInformationByHandle fills a BY_HANDLE_FILE_INFORMATION with the attribute flags, three times that include the creation time, the size, the number of links and a file index19. "The identifier (low and high parts) and the volume serial number uniquely identify a file on a single computer"19, as the device ID and the inode number do on Unix.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | |
| C++ | Standard library | |
| Java | Standard library | |
| C | Library | |
| C# | Standard library | |
| JavaScript | Standard library | |
| TypeScript | Standard library | TypeScript on Node.js uses the node:fs module, with the types from @types/node, so stat, lstat and the fs.Stats object are the same as in the JavaScript example. No example file exists. |
| Go | Standard library | |
| Rust | Standard library | |
| Kotlin | Standard library | Kotlin on the JVM uses java.nio.file, and the kotlin.io.path package adds extensions such as readAttributes, so the attribute views of the Java example do the work. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | A query works on rows in tables. The database server reads the files, but the SQL language has no operations on file metadata. |
| Bash | Native | The test operators -e, -f, -d, -L, -r, -w, -x and -s read the metadata of a file, and -nt and -ot compare the modification times. The stat command of the system prints the other fields. No example file exists. |
| PowerShell | Native | Get-Item returns a FileInfo or a DirectoryInfo object of .NET, with Length, Attributes, the times, LinkType, Target and UnixMode. No example file exists because pwsh is not installed. |
| HTML | Does not apply | A web page cannot read the metadata of a local file by a path. A file that the user chooses becomes a File object with a name, a size, a type and a lastModified time. |
| CSS | Does not apply | Style rules do not read files or their metadata. |
| Regular expressions | Does not apply | A regular expression matches text. It does not read the size, the times or the mode of a file. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | stdlib | os.stat, os.lstat, os.stat_result, the stat module; os.DirEntry; os.getxattr |
| JavaScript | stdlib | Node.js node:fs: stat, lstat and fs.Stats, with bigint: true for nanoseconds |
| TypeScript | stdlib | the node:fs module of Node.js, with the types of @types/node |
| Java | stdlib | Files.readAttributes with BasicFileAttributes, PosixFileAttributes or a view name; NOFOLLOW_LINKS |
| Kotlin | stdlib | kotlin.io.path extensions on java.nio.file.Path, so the Java attribute views do the work |
| C# | stdlib | FileSystemInfo: Attributes, the times, UnixFileMode, LinkTarget; no link count and no inode number |
| Go | stdlib | os.Stat and os.Lstat return an fs.FileInfo; Sys() gives *syscall.Stat_t on Unix |
| Rust | stdlib | fs::metadata, fs::symlink_metadata, Metadata; std::os::unix::fs::MetadataExt |
| C | library | ISO C has no metadata call; POSIX stat, lstat, fstat and struct stat; Linux statx |
| C++ | stdlib | std::filesystem::status and symlink_status, with file_size, hard_link_count and last_write_time |
| Bash | native | the tests -e, -f, -d, -L, -s, -nt and -ot; the stat command of the system |
| PowerShell | native | Get-Item returns a .NET FileInfo or DirectoryInfo object |
| SQL | n/a | a query works on rows; SQL has no operations on file metadata |
| Regex | n/a | a pattern matches text and does not read files |
| HTML | n/a | a page cannot stat a path; a File object from the user has a name, a size, a type and lastModified |
| CSS | n/a | style rules do not read files |
Each language reads the same stat structure on Unix, but each one shows a different part of it. Go's portable FileInfo has only six methods: Name, Size, Mode, ModTime, IsDir and Sys, which is the "underlying data source (can return nil)"14. Rust puts the Unix fields in a trait, MetadataExt, with methods such as dev, ino, mode, nlink, uid and gid17. Java has views: BasicFileAttributes for all file systems, and PosixFileAttributes for "File attributes associated with files on file systems used by operating systems that implement the Portable Operating System Interface (POSIX) family of standards"10. In .NET, FileSystemInfo "Provides the base class for both FileInfo and DirectoryInfo objects"13, and its LinkTarget is null if the object "doesn't represent a link"13. A C++ file_status holds only the type and the permissions18.
The example files show the two calls, stat and lstat, in each language. They also show the field that each language adds: Python's os.DirEntry, the bigint times of Node.js, the attribute views and the fileKey of Java, the FileAttributes flags of .NET, Go's Sys, Rust's MetadataExt, and the file_type::not_found status of C++.
import os
import stat
from pathlib import Path
os.mkdir("box")
os.chdir("box")
Path("data.txt").write_text("hello", encoding="utf-8")
os.chmod("data.txt", 0o640)
os.symlink("data.txt", "link")
os.symlink("missing.txt", "dangling")
# stat follows the link; lstat, or follow_symlinks=False, does not.
st = os.stat("link")
lst = os.stat("link", follow_symlinks=False)
print("stat: ", stat.filemode(st.st_mode), st.st_size)
print("lstat: ", "symlink" if stat.S_ISLNK(lst.st_mode) else "?", lst.st_size)
print("same as lstat:", lst == os.lstat("link"))
# A dangling link has metadata of its own, but no target.
try:
os.stat("dangling")
except FileNotFoundError:
print("stat dangling: FileNotFoundError")
print("lstat dangling: size", os.lstat("dangling").st_size)
# scandir gives the type of each entry without a stat call on most systems.
for e in sorted(os.scandir("."), key=lambda e: e.name):
print(f"{e.name:9} link={e.is_symlink()!s:5} file={e.is_file()!s:5}"
f" file-no-follow={e.is_file(follow_symlinks=False)}")
stat: -rw-r----- 5
lstat: symlink 8
same as lstat: True
stat dangling: FileNotFoundError
lstat dangling: size 11
dangling link=True file=False file-no-follow=False
data.txt link=False file=True file-no-follow=True
link link=True file=True file-no-follow=False
- Verdict: stdlib.
os.statreturns astat_result, andstat.filemodewrites itsst_modeaslsdoes. Withfollow_symlinks=False, or withos.lstat, the result describes the link, and the size of a link is the length of the path in it. A dangling link has no target, soos.statfails, butos.lstatworks.os.DirEntryhasis_file,is_dirandis_symlink, and each takesfollow_symlinks.
#include <filesystem>
#include <fstream>
#include <iostream>
namespace fs = std::filesystem;
static const char *kind(fs::file_type t) {
switch (t) {
case fs::file_type::regular: return "regular";
case fs::file_type::directory: return "directory";
case fs::file_type::symlink: return "symlink";
case fs::file_type::not_found: return "not_found";
default: return "other";
}
}
int main() {
std::ofstream("data.txt") << "hello";
fs::permissions("data.txt", fs::perms::owner_read | fs::perms::owner_write |
fs::perms::group_read);
fs::create_hard_link("data.txt", "second-name.txt");
fs::create_symlink("data.txt", "link");
fs::create_symlink("missing.txt", "dangling");
// status follows the link, symlink_status does not.
fs::file_status st = fs::status("link");
fs::file_status lst = fs::symlink_status("link");
std::cout << "status: " << kind(st.type()) << ", perms " << std::oct
<< static_cast<unsigned>(st.permissions()) << std::dec << "\n";
std::cout << "symlink_status: " << kind(lst.type()) << "\n";
// The other attributes come from separate calls.
std::cout << "file_size " << fs::file_size("link") << ", hard_link_count "
<< fs::hard_link_count("data.txt") << "\n";
std::cout << "equivalent: " << fs::equivalent("data.txt", "second-name.txt") << "\n";
// A missing target is a status, not an exception.
std::cout << "dangling: " << kind(fs::status("dangling").type()) << " / "
<< kind(fs::symlink_status("dangling").type()) << "\n";
}
status: regular, perms 640
symlink_status: symlink
file_size 5, hard_link_count 2
equivalent: 1
dangling: not_found / symlink
- Verdict: stdlib.
std::filesystem::statusreturns afile_status, which holds only the file type and the permissions, andsymlink_statusdoes the same without following a link. The size, the link count and the time of the last write come from the separate functionsfile_size,hard_link_countandlast_write_time. A missing file gives the typefile_type::not_found, not an exception. The standard has no owner, no inode number and no extended attributes.
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.time.Instant;
public class Main {
public static void main(String[] args) throws Exception {
Path data = Path.of("data.txt");
Files.writeString(data, "hello");
Files.setPosixFilePermissions(data, PosixFilePermissions.fromString("rw-r-----"));
Files.setLastModifiedTime(data, FileTime.from(Instant.ofEpochSecond(1700000000)));
Files.createLink(Path.of("second-name.txt"), data);
Path link = Files.createSymbolicLink(Path.of("link"), data);
// readAttributes follows the link, unless NOFOLLOW_LINKS is given.
PosixFileAttributes st = Files.readAttributes(link, PosixFileAttributes.class);
BasicFileAttributes lst = Files.readAttributes(link, BasicFileAttributes.class,
LinkOption.NOFOLLOW_LINKS);
System.out.println("stat: regular " + st.isRegularFile() + ", size " + st.size()
+ ", " + PosixFilePermissions.toString(st.permissions())
+ ", " + st.lastModifiedTime());
System.out.println("lstat: symlink " + lst.isSymbolicLink() + ", size " + lst.size());
// The unix view gives the fields that have no portable name.
System.out.println("links: " + Files.getAttribute(data, "unix:nlink"));
Object key = Files.readAttributes(Path.of("second-name.txt"),
BasicFileAttributes.class).fileKey();
System.out.println("same fileKey: " + key.equals(st.fileKey()));
}
}
stat: regular true, size 5, rw-r-----, 2023-11-14T22:13:20Z
lstat: symlink true, size 8
links: 2
same fileKey: true
- Verdict: stdlib.
Files.readAttributesreads a set of attributes in one operation. The interface that the program asks for selects the view:BasicFileAttributeshas the portable attributes, andPosixFileAttributesadds the owner, the group and the permissions.LinkOption.NOFOLLOW_LINKSreads the link itself. A string such as"unix:nlink"names one attribute in a view, andfileKeyidentifies the file, so two hard links give equal keys.
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
static const char *kind(mode_t m) {
if (S_ISREG(m)) return "regular file";
if (S_ISDIR(m)) return "directory";
if (S_ISLNK(m)) return "symbolic link";
return "other";
}
int main(void) {
FILE *f = fopen("data.txt", "w");
fputs("hello", f);
fclose(f);
chmod("data.txt", 0640);
link("data.txt", "second-name.txt");
symlink("data.txt", "link");
struct stat st, lst, other;
// stat follows the link, lstat does not.
if (stat("link", &st) != 0 || lstat("link", &lst) != 0) {
perror("stat");
return 1;
}
printf("stat: %s, size %lld, mode %03o, links %lu\n", kind(st.st_mode),
(long long)st.st_size, (unsigned)(st.st_mode & 0777),
(unsigned long)st.st_nlink);
printf("lstat: %s, size %lld\n", kind(lst.st_mode), (long long)lst.st_size);
printf("owner is me: %d\n", st.st_uid == geteuid());
stat("second-name.txt", &other);
printf("same file: %d\n", st.st_dev == other.st_dev && st.st_ino == other.st_ino);
// A dangling link: stat fails, lstat works.
symlink("missing.txt", "dangling");
printf("stat dangling: %d, lstat dangling: %d\n",
stat("dangling", &st), lstat("dangling", &lst));
return 0;
}
stat: regular file, size 5, mode 640, links 2
lstat: symbolic link, size 8
owner is me: 1
same file: 1
stat dangling: -1, lstat dangling: 0
- Verdict: library. ISO C has no call that reads the metadata of a file. POSIX
statfills astruct statfrom<sys/stat.h>, andlstatdoes the same for a link without following it. The macrosS_ISREG,S_ISDIRandS_ISLNKread the file type fromst_mode, and the low nine bits ofst_modeare the permission bits. The pairst_devandst_inoidentifies the file.
using System;
using System.IO;
File.WriteAllText("data.txt", "hello");
File.SetUnixFileMode("data.txt",
UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead);
File.SetLastWriteTimeUtc("data.txt", DateTimeOffset.FromUnixTimeSeconds(1700000000).UtcDateTime);
File.CreateSymbolicLink("link", "data.txt");
// A FileInfo for a link describes the link itself.
var link = new FileInfo("link");
Console.WriteLine($"link: target {link.LinkTarget}, size {link.Length}");
Console.WriteLine($"link attributes: {link.Attributes}");
// ResolveLinkTarget gives a FileSystemInfo for the target.
var target = (FileInfo)link.ResolveLinkTarget(returnFinalTarget: true)!;
Console.WriteLine($"target: {target.Name}, size {target.Length}");
Console.WriteLine($"mode: {target.UnixFileMode}");
Console.WriteLine($"mtime: {target.LastWriteTimeUtc:yyyy-MM-ddTHH:mm:ssZ}");
Console.WriteLine($"attributes: {target.Attributes}");
link: target data.txt, size 8
link attributes: ReparsePoint
target: data.txt, size 5
mode: GroupRead, UserWrite, UserRead
mtime: 2023-11-14T22:13:20Z
attributes: Normal
- Verdict: stdlib.
FileSystemInfois the base class ofFileInfoandDirectoryInfo, withAttributes, the three times,UnixFileModeandLinkTarget. On a symbolic link, the properties describe the link, andResolveLinkTarget(returnFinalTarget: true)gives the target.Attributesis a set ofFileAttributesflags from Windows, and on Unix, .NET makes the flags from the file type and the mode. .NET has no property for the link count or the inode number.
const fs = require("node:fs");
fs.writeFileSync("data.txt", "hello");
fs.chmodSync("data.txt", 0o640);
fs.utimesSync("data.txt", new Date(1700000000000), new Date(1700000000000));
fs.linkSync("data.txt", "second-name.txt");
fs.symlinkSync("data.txt", "link");
// statSync follows the link, lstatSync does not.
const st = fs.statSync("link");
const lst = fs.lstatSync("link");
console.log("stat: file", st.isFile(), "size", st.size,
"mode", (st.mode & 0o777).toString(8), "links", st.nlink);
console.log("lstat: symlink", lst.isSymbolicLink(), "size", lst.size);
console.log("mtime:", st.mtime.toISOString());
// The two names have one inode, so the stats are the same.
const other = fs.statSync("second-name.txt");
console.log("same file:", st.dev === other.dev && st.ino === other.ino);
// With bigint: true, the times also come in nanoseconds.
const big = fs.statSync("data.txt", { bigint: true });
console.log("mtimeNs:", big.mtimeNs);
stat: file true size 5 mode 640 links 2
lstat: symlink true size 8
mtime: 2023-11-14T22:13:20.000Z
same file: true
mtimeNs: 1700000000000000000n
- Verdict: stdlib.
fs.statSyncandfs.lstatSyncreturn anfs.Statsobject withdev,ino,mode,nlink,uid,gid,sizeand four times. The methodsisFile,isDirectoryandisSymbolicLinkread the file type frommode. Withbigint: true, the numbers arebigintvalues and the times are also in nanoseconds, such asmtimeNs.
package main
import (
"fmt"
"os"
"syscall"
"time"
)
func main() {
os.WriteFile("data.txt", []byte("hello"), 0o600)
os.Chmod("data.txt", 0o640)
t := time.Unix(1700000000, 0)
os.Chtimes("data.txt", t, t)
os.Link("data.txt", "second-name.txt")
os.Symlink("data.txt", "link")
// os.Stat follows the link, os.Lstat does not.
st, _ := os.Stat("link")
lst, _ := os.Lstat("link")
fmt.Println("stat: ", st.Name(), st.Mode(), st.Size(), st.ModTime().Unix())
fmt.Println("lstat:", lst.Name(), lst.Mode()&os.ModeSymlink != 0, lst.Size())
// Sys gives the stat structure of the system on Unix.
if sys, ok := st.Sys().(*syscall.Stat_t); ok {
fmt.Println("links:", sys.Nlink)
}
other, _ := os.Stat("second-name.txt")
fmt.Println("same file:", os.SameFile(st, other))
}
stat: link -rw-r----- 5 1700000000
lstat: link true 8
links: 2
same file: true
- Verdict: stdlib.
os.Statandos.Lstatreturn anfs.FileInfowithName,Size,Mode,ModTime,IsDirandSys.Nameis the name that the program gave, not the name of the target. TheFileModeholds the type bits and the permission bits, and it prints aslsdoes. The other fields of the stat structure, such as the link count, come fromSys, which is a*syscall.Stat_ton Unix.os.SameFilecompares twoFileInfovalues.
use std::fs;
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::time::{Duration, SystemTime};
fn main() -> std::io::Result<()> {
fs::write("data.txt", "hello")?;
fs::set_permissions("data.txt", fs::Permissions::from_mode(0o640))?;
let t = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
fs::File::options().write(true).open("data.txt")?.set_modified(t)?;
fs::hard_link("data.txt", "second-name.txt")?;
std::os::unix::fs::symlink("data.txt", "link")?;
// metadata follows the link, symlink_metadata does not.
let st = fs::metadata("link")?;
let lst = fs::symlink_metadata("link")?;
println!("metadata: file {}, len {}, mode {:o}", st.is_file(), st.len(),
st.permissions().mode() & 0o777);
println!("symlink_metadata: symlink {}, len {}", lst.file_type().is_symlink(), lst.len());
let secs = st.modified()?.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
println!("modified: {secs}");
// MetadataExt gives the fields of the Unix stat structure.
let other = fs::metadata("second-name.txt")?;
println!("nlink {}, same inode {}", st.nlink(), (st.dev(), st.ino()) == (other.dev(), other.ino()));
println!("readonly: {}", st.permissions().readonly());
Ok(())
}
metadata: file true, len 5, mode 640
symlink_metadata: symlink true, len 8
modified: 1700000000
nlink 2, same inode true
readonly: false
- Verdict: stdlib.
fs::metadatafollows a link, andfs::symlink_metadatadescribes the link. The portableMetadatahas the file type,len,permissionsand three times, andcreatedreturns an error where the system has no creation time. The traitstd::os::unix::fs::MetadataExtadds the fields of the Unix stat structure, such asdev,ino,mode,nlink,uidandgid.Permissions::readonlylooks only at the write bits, not at the user who runs the program.
Variations and related ideas
- statx. The Linux call
statxtakes a mask of the fields that the program wants, and it can return the birth time4. The answer can differ from the request: "the kernel may return fields that weren't requested and may fail to return fields that were requested, depending on what the backing filesystem supports"4. - Access control lists. An ACL gives permissions to more users than the owner and the group. On Linux, "additional security features such as Access Control Lists (ACLs) may be implemented using extended attributes"5.
- Windows attribute flags. Windows keeps a set of attribute flags in
dwFileAttributes19. .NET shows them inFileSystemInfo.Attributeson all systems13. - The file identity. The device ID and the inode number together identify a file, and a program uses them to see that two names are hard links to one file. See File system.
Pitfalls
- The change time is not the creation time.
st_ctimechanges on each change of the metadata3. Python'sst_ctimeis the "Time of most recent metadata change expressed in seconds", and on Windows, where it is deprecated, the documentation says: "Use st_birthtime for the file creation time"7. - The creation time can be missing or false. Python's
st_birthtime"is not always available, and may raise AttributeError"7. Rust'screatedreturns an error "on platforms or filesystems where it is not available"16. Node.js does not fail: where a birth time is not available,birthtime"may instead hold either the ctime or 1970-01-01T00:00Z"8. Java returns "an implementation specific default value, typically the last-modified-time or a FileTime representing the epoch (1970-01-01T00:00:00Z)"9. Do not trust a creation time that you did not check. - The access time is often not updated. "Some filesystem types allow mounting in such a way that file and/or directory accesses do not cause an update of the atime timestamp"3. Do not use the access time to find files that nobody reads.
- stat follows the link. A program that walks a tree with
statfollows the links out of the tree, and a link to a parent directory makes a loop. A dangling link has no target, sostatfails whilelstatworks. Use the form that does not follow links when the link itself matters. - The permission bits of a link have no meaning. POSIX says that for symbolic links, "The file mode bits in st_mode are unspecified"2. The values can differ between systems, so do not test them.
- The metadata can change after the call. The result describes the file at one time. Python warns that a check before an open "creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it"7. Open the file, and then use
fstaton the open descriptor. - Extended attributes are not portable. "Extended attributes are not specified in POSIX.1, but some other systems (e.g., the BSDs and Solaris) provide a similar feature"5. The kernel and the file system can also set limits on the number and the size of the attributes5. Test for the support before you use them.
Cost
A stat call is one system call. It reads the inode, which the system often has in its cache, and it does not read the data of the file. A program that lists a directory and calls stat for each name makes one more system call for each file. Python says that scandir instead of listdir "can significantly increase the performance of code that also needs file type or file attribute information, because os.DirEntry objects expose this information if the operating system provides it when scanning a directory"7. On a network file system, each call can wait for the server. Linux statx has a flag for this case: AT_STATX_DONT_SYNC takes "whatever the system has cached if possible", and "This may mean that the information returned is approximate"4.
History
Ritchie and Thompson described the i-node in their Unix paper of 1974. It holds the owner, the "protection bits", the "physical disk or tape addresses for the file contents", the size, the times, the link count, and "a code indicating whether the file is a directory, an ordinary file, or a special file"6. The stat call returned these fields to programs, and POSIX keeps them in struct stat1, with lstat for symbolic links2. The i-node of 1974 listed a "time of creation"6, but the POSIX structure has no creation time1. Linux added statx, with a mask and a birth time, in "Linux 4.11, glibc 2.28"4. Extended attributes are not in POSIX5.
References
- The Open Group, POSIX.1-2024, sys/stat.h, Description, the stat structure
- The Open Group, POSIX.1-2024, fstatat, lstat, stat, Description
- inode(7), Linux manual page, The timestamp fields
- statx(2), Linux manual page, Description; History
- xattr(7), Linux manual page, Description; Filesystem differences; Standards
- D. M. Ritchie and K. Thompson, The UNIX Time-Sharing System (1974, the BSTJ version), IV. Implementation of the file system
- The Python Standard Library, os, os.stat_result, os.scandir, os.access, Linux extended attributes
- Node.js, File system, Class fs.Stats, fs.Stats, Stat time values, fsPromises.lstat
- Java SE 25 API, java.nio.file.attribute.BasicFileAttributes, creationTime
- Java SE 25 API, java.nio.file.attribute.PosixFileAttributes, interface description
- Java SE 25 API, java.nio.file.attribute.UserDefinedFileAttributeView, interface description
- Java SE 25 API, java.nio.file.Files, readAttributes
- FileSystemInfo Class (System.IO), .NET API, Microsoft Learn, Properties
- Go standard library, package io/fs, type FileInfo
- Go standard library, package os, func Lstat
- The Rust Standard Library, std::fs::Metadata, created
- The Rust Standard Library, std::os::unix::fs::MetadataExt, trait definition
- std::filesystem::status, std::filesystem::symlink_status, cppreference.com, description
- BY_HANDLE_FILE_INFORMATION structure (fileapi.h), Win32 apps, Microsoft Learn, Members
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag X4W26P Edit this page History Report an error Markdown