取当前工作目录
char*getcwd(char *buf, int n);
#include
#include
int main(void)
{
char buffer[MAXPATH];
getcwd(buffer, MAXPATH);
printf("The current directory is: %s\n", buffer);
return 0;
}
(PHP 4, PHP 5)
getcwd — 取得当前工作目录
说明
string getcwd ( void )
取得当前工作目录。
返回值
成功则返回当前工作目录,失败返回 FALSE。
在某些 Unix 的变种下,如果任何父目录没有设定可读或搜索模式,即使当前目录设定了,getcwd() 还是会返回 FALSE。有关模式与权限的更多信息见 chmod()。
范例
Example #1 getcwd() 例子
// current directory
echo getcwd() . " ";
chdir('cvs');
// current directory
echo getcwd() . " ";
?>
以上例程的输出类似于:
/home/didou
/home/didou/cvs
参见
chdir() - 改变目录
chmod() - 改变文件模式
PHP getcwd note #1
As you could read in
the CLI SAPI does - contrary to other SAPIs - NOT automatically change the current working directory to the one the started script resides in.
A very simple workaround to regain the behaviour you're used to from your "ordinary" webpage scripting is to include something like that at the beginning of your script:
chdir( dirname ( __FILE__ ) );
?>
But because this is about reading or "finding" pathes, you might appreciate it if I share some more sophisticated tricks I frequently use in CLI scripts ...
// Note: all pathes stored in subsequent Variables end up with a DIRECTORY_SEPARATOR
// how to store the working directory "from where" the script was called:
$initial_cwd = preg_replace( '~(w)$~' , '$1' . DIRECTORY_SEPARATOR , realpath( getcwd() ) );
// how to switch symlink-free to the folder the current file resides in:
chdir( dirname ( realpath ( __FILE__ ) ) );
// how to store the former folder in a variable:
$my_folder = dirname( realpath( __FILE__ ) ) . DIRECTORY_SEPARATOR;
// how to get a path one folder up if $my_folder ends with class or /class/ :
$my_parent_folder = preg_replace( '~[/\]class[/\]$~' , DIRECTORY_SEPARATOR , $my_folder );
// how to get a path one folder up in any case :
$my_parent_folder = preg_replace( '~[/\][^/\]*[/\]$~' , DIRECTORY_SEPARATOR , $my_folder );
// how to make an array of OS-style-pathes from an array of unix-style-pathes
// (handy if you use config-files or so):
foreach( $unix_style_pathes as $unix_style_path )
$os_independent_path[] = str_replace( '/' , DIRECTORY_SEPARATOR , $unix_style_path );
?>