chdir
chdir(string $directory): bool
Changes the process working directory to the given path (relative paths resolve against the current one).
C C23
#include <libgen.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
int main(void) {
mkdir("a", 0755);
mkdir("a/b", 0755);
char buf[4096];
chdir("a"); // relative path against current cwd
printf("%s\n", basename(getcwd(buf, sizeof buf)));
chdir("b"); // now resolved inside a/
printf("%s\n", basename(getcwd(buf, sizeof buf)));
return 0;
}
a b
C++ C++26
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
fs::create_directories("a/b");
fs::current_path("a");
std::cout << fs::current_path().filename().string() << "\n";
fs::current_path("b"); // resolves inside a/
std::cout << fs::current_path().filename().string() << "\n";
return 0;
}
a b
C# v11.0.100
using System;
using System.IO;
Directory.CreateDirectory("a/b");
Environment.CurrentDirectory = Path.GetFullPath("a");
Console.WriteLine(Path.GetFileName(Directory.GetCurrentDirectory())); // a
Environment.CurrentDirectory = Path.GetFullPath("b"); // resolves inside a/
Console.WriteLine(Path.GetFileName(Directory.GetCurrentDirectory())); // b
a b
Go v1.27.4
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
if err := os.MkdirAll("a/b", 0755); err != nil {
panic(err)
}
if err := os.Chdir("a"); err != nil { // relative to current cwd
panic(err)
}
wd, err := os.Getwd()
if err != nil {
panic(err)
}
fmt.Println(filepath.Base(wd))
if err := os.Chdir("b"); err != nil { // now resolved inside a/
panic(err)
}
wd, err = os.Getwd()
if err != nil {
panic(err)
}
fmt.Println(filepath.Base(wd))
}
a b
Java v27.0.1
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws Exception {
// JVM cannot chdir; describe the steps with absolute paths instead
Path a = Path.of("a");
Path ab = a.resolve("b");
Files.createDirectories(ab);
System.out.println(a.toAbsolutePath().getFileName());
System.out.println(ab.toAbsolutePath().getFileName());
}
}
a b
JavaScript v26.13.1
const fs = require("node:fs");
const path = require("node:path");
fs.mkdirSync("a/b", { recursive: true });
process.chdir("a");
console.log(path.basename(process.cwd()));
process.chdir("b"); // resolves inside a/
console.log(path.basename(process.cwd()));
a b
PHP v8.6.0
mkdir("a/b", 0777, true);
chdir("a"); // relative to the current cwd
echo basename(getcwd()), "\n";
chdir("b"); // now resolved inside a/
echo basename(getcwd()), "\n";
a b
Python v3.15.2
import os
os.makedirs("a/b", exist_ok=True)
os.chdir("a")
print(os.path.basename(os.getcwd()))
os.chdir("b") # resolves inside a/
print(os.path.basename(os.getcwd()))
a b
Rust v1.99.1
use std::env;
use std::fs;
fn main() {
fs::create_dir_all("a/b").unwrap();
env::set_current_dir("a").unwrap();
println!("{}", env::current_dir().unwrap().file_name().unwrap().to_str().unwrap());
env::set_current_dir("b").unwrap(); // relative to the new cwd
println!("{}", env::current_dir().unwrap().file_name().unwrap().to_str().unwrap());
}
a b
TypeScript v26.13.1
import * as fs from "node:fs";
import * as path from "node:path";
fs.mkdirSync("a/b", { recursive: true });
process.chdir("a");
console.log(path.basename(process.cwd()));
process.chdir("b"); // resolves inside a/
console.log(path.basename(process.cwd()));
a b
Language differences
C: returns -1 with errno set.
C#: exposes a writable Environment.CurrentDirectory.
Go: returns an error.
Java: the JVM exception — no chdir, user.dir is fixed at launch, and child-process directories are set via ProcessBuilder.directory().
PHP: chdir changes the whole process working directory — every relative path afterwards (file opens, includes, inherited child processes) follows it, and mutating cwd in a multithreaded program is a classic race, so resolve all absolute paths you need before switching; on failure it returns false and raises E_WARNING (missing directory / no permission); relative-path semantics are the demo's core — after chdir("a"), a follow-up chdir("b") resolves to a/b, and stacked switches make relative paths error-prone, so saving the start point with getcwd first is the safe habit; demos print the basename for deterministic output (same as the getcwd entry).
Python: raises FileNotFoundError.
Rust: returns a Result.