chdir函数使用示例

时间 : 15-08-31 栏目 : linux编程 作者 : 老薛 评论 : 0 点击 : 1,364 次

一、源码

/* program p4.3.cxx: using chdir to change current working directory */

#include <stdlib.h> /*for malloc*/
#include <stdio.h> /*perror*/
#include <unistd.h>
int main(void)
{
        long cur_path_len;
        char* cur_work_dir;
        /*获得目录最大长度*/
        if((cur_path_len = pathconf(".", _PC_PATH_MAX)) == -1)
        {
                perror("Couldn't get current working path length");
                exit(1);
        }
        printf("Current Path Length Is %ld\n",cur_path_len);
        /*根据获得的目录最大长度,分配内存*/
        if((cur_work_dir = (char*)malloc(cur_path_len)) == NULL)
        {
                perror("Couldn't allocate for the pathname");
                exit(1);
        }

        if(getcwd(cur_work_dir,cur_path_len) == NULL)
        {
                perror("Couldn't get current working directory");
                exit(1);
        }

        printf("Current Working Directory Is %s\n",cur_work_dir);
          /*更改当前工作目录到上级目录*/
        if(chdir(".") == -1)
        {
                perror("Couldn't change current working directory");
                exit(1);
        }

        if(getcwd(cur_work_dir,cur_path_len) == NULL)
        {
                perror("Couldn't get current working directory");
                exit(1);
        }

        printf("After chdir function call,Current Working Directory Is %s\n",cur_work_dir);
        exit(0);

}

二、编译

gcc p4.3.c -o p4.3

三、运行

[root@gateway c_study]#./p4.3
Current Path Length Is 4096
Current Working Directory Is /home/xuekun/c_study
After chdir function call,Current Working Directory Is /home/xuekun/c_study

本文标签

除非注明,文章均为( 老薛 )原创,转载请保留链接: http://www.bdkyr.com/xtyw003/913.html

chdir函数使用示例:等您坐沙发呢!

发表评论

3 + 0 = ?


博主微信号,很高兴为您提供帮助

随便看看

为您推荐

0