basename

basename(string $path, string $suffix = ""): string

返回路径中的文件名部分。

C C23

C23
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *path = "/var/www/index.php";
    const char *base = strrchr(path, '/');
    printf("%s\n", base ? base + 1 : path);
    return 0;
}
输出
index.php

C++ C++26

C++26
#include <filesystem>
#include <iostream>
int main() {
    std::cout << std::filesystem::path("/var/www/index.php").filename().string() << "\n";
    return 0;
}
输出
index.php

C# v11.0.100

v11.0.100
Console.WriteLine(Path.GetFileName("/var/www/index.php"));
输出
index.php

Go v1.27.4

v1.27.4
package main

import (
    "fmt"
    "path"
)

func main() {
    fmt.Println(path.Base("/var/www/index.php"))
}
输出
index.php

Java v27.0.1

v27.0.1
import java.nio.file.Path;

public class Main {
    public static void main(String[] args) {
        System.out.println(Path.of("/var/www/index.php").getFileName());
    }
}
输出
index.php

JavaScript v26.13.1

v26.13.1
const path = require("node:path");
console.log(path.basename("/var/www/index.php"));
输出
index.php

PHP v8.6.0

v8.6.0
echo basename("/var/www/index.php");
输出
index.php

Python v3.15.2

v3.15.2
from pathlib import Path

print(Path("/var/www/index.php").name)
输出
index.php

Rust v1.99.1

v1.99.1
use std::path::Path;

fn main() {
    let base = Path::new("/var/www/index.php").file_name().unwrap();
    println!("{}", base.to_str().unwrap());
}
输出
index.php

TypeScript v26.13.1

v26.13.1
import * as path from "node:path";
console.log(path.basename("/var/www/index.php"));
输出
index.php

语言差异说明

C:无标准库函数,惯用手写 strrchr 定位最后一个 /,返回时跳过该字符;找不到斜杠则原样返回整串。

C++:C++17 std::filesystem::path::filename。

C#:Path.GetFileName。

Go:path.Base。

Java:Path.getFileName。

JavaScript:path.basename。

PHP:各语言内置路径工具语义一致,取「最后一个斜杠之后」;独有第二参数可剥除指定后缀,其他语言需自行后处理。

Python:Path.name。

Rust:Path::file_name。

TypeScript:同 JavaScript,path.basename。