# unix环境高级编程-chdir、fchdir和getcwd函数。

790人阅读 评论(0)

#include<unistd.h>
int chdir(const char* pathname);
int fchdir(int filedes); 

int chdir (const char *filename) [Function]
This function is used to set the process’s working directory to filename.
The normal, successful return value from chdir is 0. A value of -1 is returned to
indicate an error. The errno error conditions defined for this function are the usual
file name syntax errors (see Section 11.2.3 [File Name Errors], page 224), plus ENOTDIR
if the file filename is not a directory.
int fchdir (int filedes) [Function]
This function is used to set the process’s working directory to directory associated
with the file descriptor filedes.
The normal, successful return value from fchdir is 0. A value of -1 is returned to
indicate an error. The following errno error conditions are defined for this function:
EACCES Read permission is denied for the directory named by dirname.
EBADF The filedes argument is not a valid file descriptor.
ENOTDIR The file descriptor filedes is not associated with a directory.
EINTR The function call was interrupt by a signal.

#include"apue.h"

int main(void)
{
if(chdir("/devis/wangchenglin")<0)
err_sys("chdir failed");
printf("chdir to /devis/wangchenglin succeeded\n");
exit(0);

}


#include<unistd.h>

char *getcwd(char* buf,size_t size); 

char * getcwd (char *buffer, size t size) [Function]
The getcwd function returns an absolute file name representing the current working
directory, storing it in the character array buffer that you provide. The size argument
is how you tell the system the allocation size of buffer.
The GNU library version of this function also permits you to specify a null pointer for
the buffer argument. Then getcwd allocates a buffer automatically, as with malloc
(see Section 3.2.2 [Unconstrained Allocation], page 33). If the size is greater than
zero, then the buffer is that large; otherwise, the buffer is as large as necessary to
hold the result.
The return value is buffer on success and a null pointer on failure. The following
errno error conditions are defined for this function:
EINVAL The size argument is zero and buffer is not a null pointer.
ERANGE The size argument is less than the length of the working directory name.
You need to allocate a bigger array and try again.
EACCES Permission to read or search a component of the file name was denied.
You could implement the behavior of GNU’s getcwd (NULL, 0) using only the standard
behavior of getcwd:

char *
gnu_getcwd ()
{
size_t size = 100;

while (1)
{
char *buffer = (char *) xmalloc (size);
if (getcwd (buffer, size) == buffer)
return buffer;
free (buffer);
if (errno != ERANGE)
return 0;
size *= 2;
}
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：680169次
• 积分：9439
• 等级：
• 排名：第1898名
• 原创：203篇
• 转载：74篇
• 译文：20篇
• 评论：430条
我的GitHub
微信
duancongxd（为避免骚扰，验证注明CSDN）
我的微博
最新评论