Taskintro
Check whether a file exists
Also called file exists, test if a file exists, check that a file exists, path exists.
Tell whether a path names a file, a directory, another entry, a broken link or nothing, report an error when the program cannot tell, and know that the answer can be old at once.
- Evidence
- Code in 9 languages
Task
Tell what is at a path. Give one of five answers:
file: a regular file, also an empty one.directory: a directory.other: an entry of another type, such as a device or a named pipe.missing: there is no entry at the path.broken-link: a symbolic link whose target does not exist.
Follow symbolic links: a link to a file gives file. A path through a regular file, such as a.txt/b.txt, gives missing, because no entry can be there.
If the program cannot tell, report an error and do not give missing. For example, if a parent directory does not let the program search it, the file can be there or not, and the program cannot know which.
A check is correct only for the moment of the check. Another program can make or delete the file just after it. To make a file only if there is none, or to read a file that can be missing, do not check first: open the file and handle the error. See the pitfalls.
SQL, regular expressions, HTML and CSS do not apply, because they do not look at files.
Solutions
Each solution calls the stat function of the operating system, which follows symbolic links. If the error is ENOENT (no such entry) or ENOTDIR (a part of the path is not a directory), it calls lstat, which does not follow links, to tell a broken link from a missing entry. Each other error goes to the caller. The solutions do not use the short functions that give only true or false, because those functions give false also for an error.
- Python.
os.stat(path), thenstat.S_ISREGandstat.S_ISDIRonst_mode. On anOSErrorwitherrno.ENOENTorerrno.ENOTDIR,os.lstatandstat.S_ISLNK. The code does not useos.path.exists, which "Returns False for broken symbolic links. On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists." - JavaScript and TypeScript (Node.js).
fsPromises.stat(path)andstats.isFile(),stats.isDirectory(). On an error withcodeENOENTorENOTDIR,fsPromises.lstatandisSymbolicLink(). "fs.exists() is deprecated, but fs.existsSync() is not."fs.existsSyncgivesfalsealso for a permission error, so the code does not use it. - Java.
Files.readAttributes(path, BasicFileAttributes.class), thenisRegularFile()andisDirectory(). A missing entry givesNoSuchFileException, and a permission error givesAccessDeniedException. Java has no exception type forENOTDIR, so for anotherFileSystemExceptionthe code looks for the nearest parent that is there: if it is not a directory, the answer ismissing. The code does not useFiles.existsandFiles.notExists: "Where it is not possible to determine if a file exists or not then both methods return false." - Go.
os.Stat(path), theninfo.Mode().IsRegular()andinfo.IsDir(). On an error,errors.Is(err, fs.ErrNotExist)orerrors.Is(err, syscall.ENOTDIR), thenos.Lstatandfs.ModeSymlink. The documentation ofos.IsNotExistsays: "New code should use errors.Is(err, fs.ErrNotExist)."fs.ErrNotExistdoes not matchENOTDIR; see the pitfalls. - Rust.
std::fs::metadata(path), which "will traverse symbolic links to query information about the destination file", thenis_file()andis_dir(). On an error of kindErrorKind::NotFoundorErrorKind::NotADirectory,std::fs::symlink_metadataandfile_type().is_symlink(). The code does not usePath::exists: "If you cannot access the metadata of the file, e.g. because of a permission error or broken symbolic links, this will return false."Path::try_existsreports the error, but it does not tell a file from a directory. - C. POSIX
statandlstatwithS_ISREG,S_ISDIRandS_ISLNK. The function returns a string, orNULLwitherrnofromstatfor an error. POSIX givesENOTDIRwhen "A component of the path prefix names an existing file that is neither a directory nor a symbolic link to a directory". - C++.
std::filesystem::status(path, ec), which follows links. "If p does not exist, returns file_status ( file_type :: not_found ) ." For other errors it setsec. Thenstd::filesystem::symlink_statustells a broken link from a missing entry. The function returnsstd::expected<std::string_view, std::error_code>(C++23). - Bash. The tests
[[ -f ]],[[ -d ]],[[ -e ]]and[[ -L ]].-eis "True if pathname resolves to an existing directory entry. False if pathname cannot be resolved." It gives false also for a permission error. So for a path that seems missing, the function looks at the nearest parent that is there, and it returns status 1 if that parent is a directory that the shell cannot search.
There is no C# solution. File.GetAttributes reports Normal for a regular file, for /dev/null and for a named pipe, and .NET has no public function that gives the type of a file on Unix, so a C# solution cannot give other.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl, with the files in fixtures/.
fileandmissing: a file with text, and a name that is not there.directory: a directory givesdirectory, notfile.empty-file: an empty file is there; its size does not matter.missing-parent:fixtures/no-such-dir/a.txt. stat givesENOENT.through-a-file:fixtures/a.txt/b.txt. stat givesENOTDIR, notENOENT, but the answer ismissing.trailing-slash-on-a-directory:fixtures/dir/givesdirectory.
The native tests make the cases that need symbolic links or permissions in a temporary directory. A link to a file gives file, a link to a directory gives directory, and a link to a missing file gives broken-link. /dev/null and a named pipe give other. A path in a directory with mode 000 gives a permission error, not missing. The tests skip that case when they run as root, because root can search each directory.
Pitfalls
- A function that gives false for an error.
os.path.existsgivesFalsewhen it cannot tell. Here the name is there, but it is a loop of symbolic links, so stat fails withELOOP:
This code runs but gives a wrong answer on purpose.
import errno
import os
import tempfile
with tempfile.TemporaryDirectory() as dir:
a, b = os.path.join(dir, "a"), os.path.join(dir, "b")
os.symlink("b", a) # a loop of links: a gives b, b gives a
os.symlink("a", b)
print(os.path.exists(a), os.path.lexists(a))
try:
os.stat(a)
except OSError as err:
print(errno.errorcode[err.errno])
False True
ELOOP
A parent directory that the program cannot search gives False in the same way, as the Python documentation says. The same is true for fs.existsSync in Node.js, Files.exists in Java, Path::exists in Rust and test -e in the shell. The Java documentation of Files.notExists says: "Note that this method is not the complement of the exists method."
- A broken link takes a name.
os.path.existsgivesFalsefor a link to nothing, but the name is not free, so a new file or link with that name fails:
import os
import tempfile
with tempfile.TemporaryDirectory() as dir:
link = os.path.join(dir, "link")
os.symlink("missing.txt", link)
print(os.path.exists(link), os.path.lexists(link))
try:
os.symlink("other.txt", link) # the name is not free
except FileExistsError as err:
print(type(err).__name__)
False True
FileExistsError
- A check, then an action. The result of a check can be old when the program acts on it. This is a time-of-check to time-of-use (TOCTOU) race. Here another program makes the file between the check and the open, and the open with
"w"deletes its data. The program below does the two steps in order, to show what a race can do:
This code runs but gives a wrong answer on purpose.
import os
import tempfile
with tempfile.TemporaryDirectory() as dir:
path = os.path.join(dir, "report.txt")
if not os.path.exists(path):
# Between the check and the open, another program makes the file.
with open(path, "w") as other:
other.write("the data of another program\n")
with open(path, "w") as f: # "w" empties the file
f.write("my data\n")
print(open(path).read(), end="")
my data
Make the file and check in one step. Python mode 'x' is "open for exclusive creation, failing if the file already exists":
import os
import tempfile
with tempfile.TemporaryDirectory() as dir:
path = os.path.join(dir, "report.txt")
with open(path, "w") as other: # another program made the file first
other.write("the data of another program\n")
try:
with open(path, "x") as f: # make the file only if there is none
f.write("my data\n")
except FileExistsError:
print("the file is there; nothing is lost")
print(open(path).read(), end="")
the file is there; nothing is lost
the data of another program
The Node.js documentation says the same of access: "Using fsPromises.access() to check for the accessibility of a file before calling fsPromises.open() is not recommended. Doing so introduces a race condition, since other processes may change the file's state between the two calls."
ENOTDIRis notENOENT. In Go,errors.Is(err, fs.ErrNotExist)is true forENOENTbut not forENOTDIR. A path through a regular file givesENOTDIR:
This code runs but gives a wrong answer on purpose.
package main
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
)
func main() {
dir, _ := os.MkdirTemp("", "notdir")
defer os.RemoveAll(dir)
file := filepath.Join(dir, "a.txt")
os.WriteFile(file, []byte("alpha\n"), 0o644)
_, err := os.Stat(filepath.Join(file, "b.txt")) // a path through a file
fmt.Println(errors.Is(err, fs.ErrNotExist))
fmt.Println(errors.Unwrap(err))
}
false
not a directory
A program that reports each error that is not fs.ErrNotExist then reports an error for a path that cannot exist. The Go solution checks syscall.ENOTDIR too.
- A path is not the same in each language. Java
Path.of("a.txt/")drops the trailing slash, so it names the filea.txt, but POSIX stat ofa.txt/givesENOTDIR. JavaPath.of("")is the current directory, but POSIX stat of an empty string givesENOENT: "A component of path does not name an existing file or path is an empty string." The cases do not use these paths.
Related tasks
- Read a whole file
- Delete a file
- Create a temporary file
- Get the size of a file
- File metadata
- Hard links and symbolic links
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-file-exists/.
import errno
import os
import stat
def file_status(path: str | os.PathLike) -> str:
"""Tells what is at path: file, directory, other, missing or broken-link.
os.path.exists is not used, because it gives False also for a permission
error. Here each error other than "no such entry" comes out as an OSError.
"""
try:
mode = os.stat(path).st_mode # follows symbolic links
except OSError as err:
if err.errno not in (errno.ENOENT, errno.ENOTDIR):
raise
try:
if stat.S_ISLNK(os.lstat(path).st_mode):
return "broken-link"
except OSError:
pass
return "missing"
if stat.S_ISREG(mode):
return "file"
if stat.S_ISDIR(mode):
return "directory"
return "other"
test_file_status.py 65 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-file-exists/.
import os
from pathlib import Path
import pytest
from file_status import file_status
@pytest.fixture
def tree(tmp_path: Path) -> Path:
(tmp_path / "a.txt").write_text("alpha\n")
(tmp_path / "empty.txt").write_bytes(b"")
(tmp_path / "dir").mkdir()
return tmp_path
CASES = {
"a.txt": "file",
"empty.txt": "file",
"dir": "directory",
"dir/": "directory",
"missing.txt": "missing",
"no-such-dir/a.txt": "missing",
"a.txt/b.txt": "missing",
}
@pytest.mark.parametrize("name", CASES)
def test_status(tree: Path, name: str) -> None:
assert file_status(os.path.join(tree, name)) == CASES[name]
def test_links(tree: Path) -> None:
(tree / "to-file").symlink_to("a.txt")
(tree / "to-dir").symlink_to("dir")
(tree / "to-nothing").symlink_to("missing.txt")
assert file_status(tree / "to-file") == "file"
assert file_status(tree / "to-dir") == "directory"
assert file_status(tree / "to-nothing") == "broken-link"
@pytest.mark.skipif(not os.path.exists("/dev/null"), reason="no /dev/null")
def test_device() -> None:
assert file_status("/dev/null") == "other"
def test_named_pipe(tree: Path) -> None:
os.mkfifo(tree / "pipe")
assert file_status(tree / "pipe") == "other"
@pytest.mark.skipif(os.geteuid() == 0, reason="root can search each directory")
def test_permission_error(tree: Path) -> None:
locked = tree / "locked"
locked.mkdir()
(locked / "a.txt").write_text("alpha\n")
locked.chmod(0o000)
try:
with pytest.raises(PermissionError):
file_status(locked / "a.txt")
finally:
locked.chmod(0o700)
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-file-exists/.
// since: C++23 (std::expected)
#include "file_status.hpp"
namespace fs = std::filesystem;
std::expected<std::string_view, std::error_code> file_status(const fs::path& path) {
std::error_code ec;
// status follows symbolic links. For a path that does not exist, it gives
// file_type::not_found and no error; for other errors, file_type::none.
fs::file_status st = fs::status(path, ec);
if (st.type() == fs::file_type::not_found) {
std::error_code lec;
return fs::is_symlink(fs::symlink_status(path, lec)) ? "broken-link" : "missing";
}
if (ec) return std::unexpected(ec);
if (fs::is_regular_file(st)) return "file";
if (fs::is_directory(st)) return "directory";
return "other";
}
file_status.hpp 15 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-file-exists/.
// since: C++23 (std::expected)
#pragma once
#include <expected>
#include <filesystem>
#include <string_view>
#include <system_error>
// Tells what is at path: "file", "directory", "other", "missing" or
// "broken-link". On an error other than "no such entry", for example a
// permission error, it gives the error code.
std::expected<std::string_view, std::error_code> file_status(const std::filesystem::path& path);
test_file_status.cpp 71 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-file-exists/.
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <string>
#include <system_error>
#include <unistd.h>
#include "file_status.hpp"
namespace fs = std::filesystem;
namespace {
const fs::path dir = "file_status_tree";
int failures = 0;
void check(const std::string& path, std::string_view want) {
auto got = file_status(path);
if (!got || *got != want) {
std::fprintf(stderr, "file_status(%s) is wrong\n", path.c_str());
failures++;
}
}
} // namespace
int main() {
fs::remove_all(dir);
fs::create_directories(dir / "dir");
std::ofstream(dir / "a.txt") << "alpha\n";
std::ofstream(dir / "empty.txt").close();
const std::string d = dir.string() + "/";
check(d + "a.txt", "file");
check(d + "empty.txt", "file");
check(d + "dir", "directory");
check(d + "dir/", "directory");
check(d + "missing.txt", "missing");
check(d + "no-such-dir/a.txt", "missing");
check(d + "a.txt/b.txt", "missing");
fs::create_symlink("a.txt", dir / "to-file");
fs::create_directory_symlink("dir", dir / "to-dir");
fs::create_symlink("missing.txt", dir / "to-nothing");
check(d + "to-file", "file");
check(d + "to-dir", "directory");
check(d + "to-nothing", "broken-link");
if (fs::exists("/dev/null")) check("/dev/null", "other");
if (std::system(("mkfifo " + d + "pipe").c_str()) != 0) return 2;
check(d + "pipe", "other");
if (geteuid() != 0) {
fs::create_directory(dir / "locked");
std::ofstream(dir / "locked" / "a.txt") << "alpha\n";
fs::permissions(dir / "locked", fs::perms::none);
auto got = file_status(dir / "locked" / "a.txt");
if (got || got.error() != std::errc::permission_denied) {
std::fputs("locked: want permission_denied\n", stderr);
failures++;
}
fs::permissions(dir / "locked", fs::perms::owner_all);
}
fs::remove_all(dir);
if (failures > 0) return 1;
std::puts("ok");
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-file-exists/.
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
public final class FileStatus {
private FileStatus() {}
/**
* Tells what is at path: "file", "directory", "other", "missing" or "broken-link".
*
* <p>Files.exists is not used, because it gives false also when it cannot tell. Here each error
* other than "no such entry" comes out as an IOException.
*/
public static String of(Path path) throws IOException {
BasicFileAttributes attrs;
try {
attrs = Files.readAttributes(path, BasicFileAttributes.class); // follows links
} catch (NoSuchFileException e) {
return isLink(path) ? "broken-link" : "missing";
} catch (AccessDeniedException e) {
throw e;
} catch (FileSystemException e) {
// Java has no exception type for ENOTDIR. A path through a regular file
// has no entry, so look for the nearest parent that is there.
if (throughAFile(path)) {
return "missing";
}
throw e;
}
if (attrs.isRegularFile()) {
return "file";
}
if (attrs.isDirectory()) {
return "directory";
}
return "other";
}
private static boolean isLink(Path path) {
try {
return Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS)
.isSymbolicLink();
} catch (IOException e) {
return false;
}
}
private static boolean throughAFile(Path path) {
for (Path p = path.getParent(); p != null; p = p.getParent()) {
if (Files.exists(p)) {
return !Files.isDirectory(p);
}
}
return false;
}
}
FileStatusTest.java 79 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-file-exists/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermissions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class FileStatusTest {
@TempDir Path dir;
@BeforeEach
void tree() throws IOException {
Files.writeString(dir.resolve("a.txt"), "alpha\n");
Files.writeString(dir.resolve("empty.txt"), "");
Files.createDirectory(dir.resolve("dir"));
}
@ParameterizedTest(name = "{0}")
@CsvSource({
"a.txt, file",
"empty.txt, file",
"dir, directory",
"dir/, directory",
"missing.txt, missing",
"no-such-dir/a.txt, missing",
"a.txt/b.txt, missing",
})
void status(String name, String want) throws IOException {
assertEquals(want, FileStatus.of(dir.resolve(name)));
}
@Test
void links() throws IOException {
Files.createSymbolicLink(dir.resolve("to-file"), Path.of("a.txt"));
Files.createSymbolicLink(dir.resolve("to-dir"), Path.of("dir"));
Files.createSymbolicLink(dir.resolve("to-nothing"), Path.of("missing.txt"));
assertEquals("file", FileStatus.of(dir.resolve("to-file")));
assertEquals("directory", FileStatus.of(dir.resolve("to-dir")));
assertEquals("broken-link", FileStatus.of(dir.resolve("to-nothing")));
}
@Test
void device() throws IOException {
assumeTrue(Files.exists(Path.of("/dev/null")));
assertEquals("other", FileStatus.of(Path.of("/dev/null")));
}
@Test
void namedPipe() throws Exception {
Path pipe = dir.resolve("pipe");
assertEquals(0, new ProcessBuilder("mkfifo", pipe.toString()).start().waitFor());
assertEquals("other", FileStatus.of(pipe));
}
@Test
void permissionError() throws IOException {
assumeFalse("root".equals(System.getProperty("user.name")));
Path locked = Files.createDirectory(dir.resolve("locked"));
Files.writeString(locked.resolve("a.txt"), "alpha\n");
Files.setPosixFilePermissions(locked, PosixFilePermissions.fromString("---------"));
try {
assertThrows(AccessDeniedException.class, () -> FileStatus.of(locked.resolve("a.txt")));
} finally {
Files.setPosixFilePermissions(locked, PosixFilePermissions.fromString("rwx------"));
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-file-exists/.
// stat and lstat are in POSIX.1-2008, not in ISO C.
#define _POSIX_C_SOURCE 200809L
#include "file_status.h"
#include <errno.h>
#include <stddef.h>
#include <sys/stat.h>
const char *file_status(const char *path) {
struct stat st;
if (stat(path, &st) != 0) {
// ENOTDIR: a part of the path before the last one is not a directory.
if (errno != ENOENT && errno != ENOTDIR) return NULL;
if (lstat(path, &st) == 0 && S_ISLNK(st.st_mode)) return "broken-link";
return "missing";
}
if (S_ISREG(st.st_mode)) return "file";
if (S_ISDIR(st.st_mode)) return "directory";
return "other";
}
file_status.h 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-file-exists/.
#ifndef FILE_STATUS_H
#define FILE_STATUS_H
// file_status tells what is at path: "file", "directory", "other", "missing"
// or "broken-link". It follows symbolic links. On an error other than "no
// such entry", for example EACCES, it returns NULL and keeps errno from stat.
const char *file_status(const char *path);
#endif
test_file_status.c 85 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-file-exists/.
// mkfifo, symlink and geteuid are in POSIX.1-2008, not in ISO C.
#define _POSIX_C_SOURCE 200809L
#include "file_status.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
static const char *dir = "file_status_tree";
static int failures = 0;
static const char *at(const char *name) {
static char path[256];
snprintf(path, sizeof path, "%s/%s", dir, name);
return path;
}
static void touch(const char *name, const char *text) {
FILE *f = fopen(at(name), "w");
if (f == NULL || fputs(text, f) < 0 || fclose(f) != 0) exit(2);
}
static void check(const char *path, const char *want) {
const char *got = file_status(path);
if (got == NULL || strcmp(got, want) != 0) {
fprintf(stderr, "file_status(%s) = %s, want %s\n", path, got ? got : "NULL", want);
failures++;
}
}
int main(void) {
if (system("rm -rf file_status_tree") != 0 || mkdir(dir, 0755) != 0) return 2;
touch("a.txt", "alpha\n");
touch("empty.txt", "");
mkdir(at("dir"), 0755);
check(at("a.txt"), "file");
check(at("empty.txt"), "file");
check(at("dir"), "directory");
check(at("dir/"), "directory");
check(at("missing.txt"), "missing");
check(at("no-such-dir/a.txt"), "missing");
check(at("a.txt/b.txt"), "missing");
char link[256];
snprintf(link, sizeof link, "%s", at("to-file"));
symlink("a.txt", link);
check(link, "file");
snprintf(link, sizeof link, "%s", at("to-dir"));
symlink("dir", link);
check(link, "directory");
snprintf(link, sizeof link, "%s", at("to-nothing"));
symlink("missing.txt", link);
check(link, "broken-link");
if (access("/dev/null", F_OK) == 0) check("/dev/null", "other");
snprintf(link, sizeof link, "%s", at("pipe"));
if (mkfifo(link, 0644) != 0) return 2;
check(link, "other");
if (geteuid() != 0) {
char locked[256];
snprintf(locked, sizeof locked, "%s", at("locked"));
mkdir(locked, 0755);
touch("locked/a.txt", "alpha\n");
chmod(locked, 0);
errno = 0;
const char *got = file_status(at("locked/a.txt"));
if (got != NULL || errno != EACCES) {
fprintf(stderr, "locked: got %s, errno %d, want NULL, EACCES\n", got ? got : "NULL", errno);
failures++;
}
chmod(locked, 0700);
}
if (system("rm -rf file_status_tree") != 0) return 2;
if (failures > 0) return 1;
puts("ok");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-file-exists/.
import { lstat, stat } from "node:fs/promises";
/**
* Tells what is at path: "file", "directory", "other", "missing" or
* "broken-link". fs.existsSync is not used, because it gives false also for a
* permission error. Here each error other than "no such entry" is thrown.
*/
export async function fileStatus(path) {
let info;
try {
info = await stat(path); // follows symbolic links
} catch (err) {
if (err.code !== "ENOENT" && err.code !== "ENOTDIR") throw err;
try {
if ((await lstat(path)).isSymbolicLink()) return "broken-link";
} catch {
// There is no entry at all.
}
return "missing";
}
if (info.isFile()) return "file";
if (info.isDirectory()) return "directory";
return "other";
}
fileStatus.test.js 71 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-file-exists/.
import { test } from "node:test";
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { existsSync } from "node:fs";
import { chmod, mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileStatus } from "./fileStatus.js";
async function withTree(fn) {
const dir = await mkdtemp(join(tmpdir(), "file-status-"));
try {
await writeFile(join(dir, "a.txt"), "alpha\n");
await writeFile(join(dir, "empty.txt"), "");
await mkdir(join(dir, "dir"));
await fn(dir);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
const cases = {
"a.txt": "file",
"empty.txt": "file",
dir: "directory",
"dir/": "directory",
"missing.txt": "missing",
"no-such-dir/a.txt": "missing",
"a.txt/b.txt": "missing",
};
for (const [name, want] of Object.entries(cases)) {
// join keeps a trailing slash.
test(name, () => withTree(async (dir) => assert.equal(await fileStatus(join(dir, name)), want)));
}
test("symbolic links", () =>
withTree(async (dir) => {
await symlink("a.txt", join(dir, "to-file"));
await symlink("dir", join(dir, "to-dir"));
await symlink("missing.txt", join(dir, "to-nothing"));
assert.equal(await fileStatus(join(dir, "to-file")), "file");
assert.equal(await fileStatus(join(dir, "to-dir")), "directory");
assert.equal(await fileStatus(join(dir, "to-nothing")), "broken-link");
}));
test("device", { skip: !existsSync("/dev/null") && "no /dev/null" }, async () => {
assert.equal(await fileStatus("/dev/null"), "other");
});
test("named pipe", () =>
withTree(async (dir) => {
execFileSync("mkfifo", [join(dir, "pipe")]);
assert.equal(await fileStatus(join(dir, "pipe")), "other");
}));
test("permission error", { skip: process.getuid?.() === 0 && "root can search each directory" }, () =>
withTree(async (dir) => {
const locked = join(dir, "locked");
await mkdir(locked);
await writeFile(join(locked, "a.txt"), "alpha\n");
await chmod(locked, 0o000);
try {
await assert.rejects(fileStatus(join(locked, "a.txt")), { code: "EACCES" });
} finally {
await chmod(locked, 0o700);
}
}));
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-file-exists/.
import type { Stats } from "node:fs";
import { lstat, stat } from "node:fs/promises";
/**
* Tells what is at path: "file", "directory", "other", "missing" or
* "broken-link". fs.existsSync is not used, because it gives false also for a
* permission error. Here each error other than "no such entry" is thrown.
*/
export type FileStatus = "file" | "directory" | "other" | "missing" | "broken-link";
export async function fileStatus(path: string): Promise<FileStatus> {
let info: Stats;
try {
info = await stat(path); // follows symbolic links
} catch (err) {
const code = (err as NodeJS.ErrnoException).code;
if (code !== "ENOENT" && code !== "ENOTDIR") throw err;
try {
if ((await lstat(path)).isSymbolicLink()) return "broken-link";
} catch {
// There is no entry at all.
}
return "missing";
}
if (info.isFile()) return "file";
if (info.isDirectory()) return "directory";
return "other";
}
fileStatus.test.ts 71 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-file-exists/.
import { test } from "node:test";
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { existsSync } from "node:fs";
import { chmod, mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileStatus } from "./fileStatus.ts";
async function withTree(fn: (dir: string) => Promise<void>): Promise<void> {
const dir = await mkdtemp(join(tmpdir(), "file-status-"));
try {
await writeFile(join(dir, "a.txt"), "alpha\n");
await writeFile(join(dir, "empty.txt"), "");
await mkdir(join(dir, "dir"));
await fn(dir);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
const cases: Record<string, string> = {
"a.txt": "file",
"empty.txt": "file",
dir: "directory",
"dir/": "directory",
"missing.txt": "missing",
"no-such-dir/a.txt": "missing",
"a.txt/b.txt": "missing",
};
for (const [name, want] of Object.entries(cases)) {
// join keeps a trailing slash.
test(name, () => withTree(async (dir) => assert.equal(await fileStatus(join(dir, name)), want)));
}
test("symbolic links", () =>
withTree(async (dir) => {
await symlink("a.txt", join(dir, "to-file"));
await symlink("dir", join(dir, "to-dir"));
await symlink("missing.txt", join(dir, "to-nothing"));
assert.equal(await fileStatus(join(dir, "to-file")), "file");
assert.equal(await fileStatus(join(dir, "to-dir")), "directory");
assert.equal(await fileStatus(join(dir, "to-nothing")), "broken-link");
}));
test("device", { skip: !existsSync("/dev/null") && "no /dev/null" }, async () => {
assert.equal(await fileStatus("/dev/null"), "other");
});
test("named pipe", () =>
withTree(async (dir) => {
execFileSync("mkfifo", [join(dir, "pipe")]);
assert.equal(await fileStatus(join(dir, "pipe")), "other");
}));
test("permission error", { skip: process.getuid?.() === 0 && "root can search each directory" }, () =>
withTree(async (dir) => {
const locked = join(dir, "locked");
await mkdir(locked);
await writeFile(join(locked, "a.txt"), "alpha\n");
await chmod(locked, 0o000);
try {
await assert.rejects(fileStatus(join(locked, "a.txt")), { code: "EACCES" });
} finally {
await chmod(locked, 0o700);
}
}));
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-file-exists/.
// Package filestatus tells what is at a path.
package filestatus
import (
"errors"
"io/fs"
"os"
"syscall"
)
// FileStatus tells what is at path: "file", "directory", "other", "missing"
// or "broken-link". Each error other than "no such entry" is returned.
//
// errors.Is(err, fs.ErrNotExist) is true for ENOENT but not for ENOTDIR,
// which a path through a regular file gives, so the code checks both.
func FileStatus(path string) (string, error) {
info, err := os.Stat(path) // follows symbolic links
if err != nil {
if !errors.Is(err, fs.ErrNotExist) && !errors.Is(err, syscall.ENOTDIR) {
return "", err
}
if l, lerr := os.Lstat(path); lerr == nil && l.Mode()&fs.ModeSymlink != 0 {
return "broken-link", nil
}
return "missing", nil
}
switch {
case info.Mode().IsRegular():
return "file", nil
case info.IsDir():
return "directory", nil
default:
return "other", nil
}
}
file_status_test.go 89 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-file-exists/.
package filestatus
import (
"errors"
"io/fs"
"os"
"path/filepath"
"syscall"
"testing"
)
func tree(t *testing.T) string {
t.Helper()
dir := t.TempDir()
must(t, os.WriteFile(filepath.Join(dir, "a.txt"), []byte("alpha\n"), 0o644))
must(t, os.WriteFile(filepath.Join(dir, "empty.txt"), nil, 0o644))
must(t, os.Mkdir(filepath.Join(dir, "dir"), 0o755))
return dir
}
func must(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
func check(t *testing.T, path, want string) {
t.Helper()
got, err := FileStatus(path)
if err != nil || got != want {
t.Fatalf("FileStatus(%q) = %q, %v; want %q", path, got, err, want)
}
}
func TestStatus(t *testing.T) {
dir := tree(t)
for name, want := range map[string]string{
"a.txt": "file",
"empty.txt": "file",
"dir": "directory",
"dir/": "directory",
"missing.txt": "missing",
"no-such-dir/a.txt": "missing",
"a.txt/b.txt": "missing",
} {
check(t, dir+"/"+name, want) // filepath.Join drops a trailing slash
}
}
func TestLinks(t *testing.T) {
dir := tree(t)
must(t, os.Symlink("a.txt", filepath.Join(dir, "to-file")))
must(t, os.Symlink("dir", filepath.Join(dir, "to-dir")))
must(t, os.Symlink("missing.txt", filepath.Join(dir, "to-nothing")))
check(t, filepath.Join(dir, "to-file"), "file")
check(t, filepath.Join(dir, "to-dir"), "directory")
check(t, filepath.Join(dir, "to-nothing"), "broken-link")
}
func TestDevice(t *testing.T) {
if _, err := os.Lstat("/dev/null"); err != nil {
t.Skip("no /dev/null")
}
check(t, "/dev/null", "other")
}
func TestNamedPipe(t *testing.T) {
pipe := filepath.Join(tree(t), "pipe")
must(t, syscall.Mkfifo(pipe, 0o644))
check(t, pipe, "other")
}
func TestPermissionError(t *testing.T) {
if os.Geteuid() == 0 {
t.Skip("root can search each directory")
}
locked := filepath.Join(tree(t), "locked")
must(t, os.Mkdir(locked, 0o755))
must(t, os.WriteFile(filepath.Join(locked, "a.txt"), []byte("alpha\n"), 0o644))
must(t, os.Chmod(locked, 0))
defer os.Chmod(locked, 0o700)
if _, err := FileStatus(filepath.Join(locked, "a.txt")); !errors.Is(err, fs.ErrPermission) {
t.Fatalf("err = %v, want fs.ErrPermission", err)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-file-exists/.
use std::fs;
use std::io::{self, ErrorKind};
use std::path::Path;
/// Tells what is at `path`: "file", "directory", "other", "missing" or
/// "broken-link".
///
/// `Path::exists` is not used, because it gives false also for a permission
/// error. `Path::try_exists` reports that error, but it does not tell a
/// file from a directory. Here each error other than "no such entry" is
/// returned.
pub fn file_status(path: impl AsRef<Path>) -> io::Result<&'static str> {
let path = path.as_ref();
let meta = match fs::metadata(path) {
// metadata follows symbolic links.
Ok(meta) => meta,
Err(e) if matches!(e.kind(), ErrorKind::NotFound | ErrorKind::NotADirectory) => {
let is_link = fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink());
return Ok(if is_link { "broken-link" } else { "missing" });
}
Err(e) => return Err(e),
};
Ok(if meta.is_file() {
"file"
} else if meta.is_dir() {
"directory"
} else {
"other"
})
}
tests/file_status_test.rs 82 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-file-exists/.
use std::fs;
use std::io::ErrorKind;
use std::os::unix::fs::{symlink, PermissionsExt};
use std::path::{Path, PathBuf};
use std::process::Command;
use algo_check_whether_a_file_exists::file_status;
/// Returns a new directory with a.txt, empty.txt and dir in it.
fn tree(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("file-status-{}-{name}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(dir.join("dir")).unwrap();
fs::write(dir.join("a.txt"), "alpha\n").unwrap();
fs::write(dir.join("empty.txt"), "").unwrap();
dir
}
#[test]
fn status() {
let dir = tree("status");
for (name, want) in [
("a.txt", "file"),
("empty.txt", "file"),
("dir", "directory"),
("dir/", "directory"),
("missing.txt", "missing"),
("no-such-dir/a.txt", "missing"),
("a.txt/b.txt", "missing"),
] {
assert_eq!(file_status(dir.join(name)).unwrap(), want, "{name}");
}
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn links() {
let dir = tree("links");
symlink("a.txt", dir.join("to-file")).unwrap();
symlink("dir", dir.join("to-dir")).unwrap();
symlink("missing.txt", dir.join("to-nothing")).unwrap();
assert_eq!(file_status(dir.join("to-file")).unwrap(), "file");
assert_eq!(file_status(dir.join("to-dir")).unwrap(), "directory");
assert_eq!(file_status(dir.join("to-nothing")).unwrap(), "broken-link");
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn device() {
if Path::new("/dev/null").exists() {
assert_eq!(file_status("/dev/null").unwrap(), "other");
}
}
#[test]
fn named_pipe() {
let dir = tree("pipe");
let pipe = dir.join("pipe");
assert!(Command::new("mkfifo").arg(&pipe).status().unwrap().success());
assert_eq!(file_status(&pipe).unwrap(), "other");
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn permission_error() {
let dir = tree("locked");
let locked = dir.join("locked");
fs::create_dir(&locked).unwrap();
fs::write(locked.join("a.txt"), "alpha\n").unwrap();
fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).unwrap();
// Root can search each directory, so there is no error for root.
let root = fs::read_dir(&locked).is_ok();
let got = file_status(locked.join("a.txt"));
fs::set_permissions(&locked, fs::Permissions::from_mode(0o700)).unwrap();
if !root {
assert_eq!(got.unwrap_err().kind(), ErrorKind::PermissionDenied);
}
fs::remove_dir_all(&dir).unwrap();
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-file-exists/.
# file_status NAME PATH
# Stores what is at PATH in the variable NAME: file, directory, other,
# missing or broken-link. The tests -f, -d and -e follow symbolic links, and
# -L does not. Each test gives false also when it cannot tell, for example
# when a parent directory cannot be searched. So for a path that seems
# missing, the function looks at the nearest parent that is there. If that
# parent is a directory that the shell cannot search, it returns status 1 and
# does not set NAME.
file_status() {
local _file_status _parent
if [[ -f $2 ]]; then
_file_status=file
elif [[ -d $2 ]]; then
_file_status=directory
elif [[ -e $2 ]]; then
_file_status=other
elif [[ -L $2 ]]; then
_file_status=broken-link
else
_parent=$2
while [[ $_parent != / && $_parent != . ]]; do
_parent=$(dirname -- "$_parent")
[[ -e $_parent || -L $_parent ]] && break
done
if [[ -d $_parent && ! -x $_parent ]]; then
printf 'file_status: %s: cannot search the directory %s\n' "$2" "$_parent" >&2
return 1
fi
_file_status=missing
fi
printf -v "$1" '%s' "$_file_status"
}
test_file_status.bats 55 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-file-exists/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/file_status.sh"
dir=$BATS_TEST_TMPDIR
printf 'alpha\n' >"$dir/a.txt"
: >"$dir/empty.txt"
mkdir "$dir/dir"
}
check() { # check PATH WANT
local got
file_status got "$1"
[ "$got" = "$2" ]
}
@test "file" { check "$dir/a.txt" file; }
@test "empty file" { check "$dir/empty.txt" file; }
@test "directory" { check "$dir/dir" directory; }
@test "trailing slash" { check "$dir/dir/" directory; }
@test "missing" { check "$dir/missing.txt" missing; }
@test "missing parent" { check "$dir/no-such-dir/a.txt" missing; }
@test "through a file" { check "$dir/a.txt/b.txt" missing; }
@test "symbolic links" {
ln -s a.txt "$dir/to-file"
ln -s dir "$dir/to-dir"
ln -s missing.txt "$dir/to-nothing"
check "$dir/to-file" file
check "$dir/to-dir" directory
check "$dir/to-nothing" broken-link
}
@test "device" {
[ -e /dev/null ] || skip "no /dev/null"
check /dev/null other
}
@test "named pipe" {
mkfifo "$dir/pipe"
check "$dir/pipe" other
}
@test "permission error" {
[ "$(id -u)" -ne 0 ] || skip "root can search each directory"
mkdir "$dir/locked"
printf 'alpha\n' >"$dir/locked/a.txt"
chmod 000 "$dir/locked"
run -1 file_status got "$dir/locked/a.txt"
chmod 700 "$dir/locked"
}
References
- The Python Standard Library, os.path, Common pathname manipulations, os.path.exists, os.path.lexists
- The Python Standard Library, os, Miscellaneous operating system interfaces, os.stat, os.lstat
- The Python Standard Library, Built-in Functions, open, the mode 'x'
- Node.js documentation, File system, fsPromises.access(path[, mode]), fsPromises.stat(path[, options]), fs.existsSync(path)
- Java SE 25 API, Files, exists(Path, LinkOption...), notExists(Path, LinkOption...), readAttributes(Path, Class, LinkOption...)
- Go standard library, package os, func IsNotExist, func Stat, func Lstat
- Go standard library, package io/fs, ErrNotExist, type FileMode
- The Rust Standard Library, std::path::Path, exists, try_exists
- The Rust Standard Library, std::fs::metadata, the function documentation
- The Open Group Base Specifications Issue 8 (POSIX.1-2024), fstatat, lstat, stat, ERRORS
- The Open Group Base Specifications Issue 8 (POSIX.1-2024), test, OPERANDS (-e, -L)
- cppreference, std::filesystem::status, std::filesystem::symlink_status, Return value
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 |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag KBHB5J Edit this page History Report an error Markdown