basename

Section: C Library Functions (3)
Updated: 2026-02-08
Index JM Home Page roff page
 

名前

basename, dirname - パス名を解析して各部分を取り出す  

ライブラリ

標準 C ライブラリ (libc,~-lc)  

書式

#include <libgen.h>

char *dirname(char *path);
char *basename(char *path);
 

説明

Warning: there are two different functions basename(); see below.

The functions dirname() and basename() break a null-terminated pathname string into directory and filename components. In the usual case, dirname() returns the string up to, but not including, the final '/', and basename() returns the component following the final '/'. Trailing '/' characters are not counted as part of the pathname.

path に '/' 文字がない場合は、 dirname() は文字列 "." を返し、 basename() は path と同じ内容を返す。 path が文字列 "/" に等しい場合は、 dirname() も basename() も文字列 "/" を返す。 path が ヌルポインターだったり、空の文字列を指していた場合は、 dirname() も basename() も文字列 "." を返す。

dirname() の返した文字列、 "/"、 basename() の返した文字列、 を順に結合すると、完全なパス名が得られる。

dirname() と basename() は、いずれも path の内容を変更することがある。 したがって、これらの関数を呼び出す際には コピーを渡すのが望ましい。

これらの関数は、静的に割り当てられたメモリーへのポインターを返すことがあり、 これらの領域は後の関数呼び出しで上書きされるかもしれない。 また、これらの関数は path の一部分を指すポインターを返すこともある。そのため、 path で参照される文字列は、関数が返すポインターが不要になるまでは 変更したり free したりすべきではない。

以下の一連の例 (SUSv2 から引用) は、 いろいろな path に対して dirname() と basename() が返す文字列を表したものである。

pathdirnamebasename
/usr/lib/usrlib
/usr//usr
usr.usr
///
...
.....
 

返り値

dirname() と basename() は、いずれもヌルで終端された文字列へのポインターを返す。 (これらのポインターを free(3) に渡さないこと。)  

属性

この節で使用されている用語の説明については、 attributes(7) を参照。
インターフェース属性値
basename(), dirname() Thread safetyMT-Safe
 

バージョン

basename() には 2種類の異なるバージョンがある。 一つはすでに説明した POSIX バージョンであり、 もう一つは GNU バージョンである。 GNU バージョンを使用するには以下のようにする。

    #define _GNU_SOURCE         /* feature_test_macros(7) 参照 */
#include <string.h>

GNU バージョンは引数を変更することはなく、 path の末尾が '/'の場合は空の文字列を返す。 特に path が "/" の場合も空文字列を返す。 dirname() には GNU バージョンはない。

glibc では、 <libgen.h> をインクルードすると POSIX バージョンの basename() が使用され、それ以外の場合は GNU バージョンとなる。  

標準規格

POSIX.1-2008.  

歴史

POSIX.1-2001.  

バグ

glibc の実装では、これらの関数の POSIX バージョンは path 引数が変更され、 "/usr/" などの静的文字列を指定されるとセグメンテーションフォールトを起こす。

Before glibc 2.2.1, the glibc version of dirname() did not correctly handle pathnames with trailing '/' characters, and generated a segfault if given a NULL argument.  

例

The following code snippet demonstrates the use of basename() and dirname():
char *dirc, *basec, *bname, *dname;
char *path = "/etc/passwd";

dirc = strdup(path);
basec = strdup(path);
dname = dirname(dirc);
bname = basename(basec);
printf("dirname=%s, basename=%s\n", dname, bname);
 

関連項目

basename(1), dirname(1)


 

Index

名前
ライブラリ
書式
説明
返り値
属性
バージョン
標準規格
歴史
バグ
例
関連項目

This document was created by man2html, using the manual pages.