首页 > 其他 > 详细

目录管理

时间:2016-01-14 20:58:13      阅读:181      评论:0      收藏:0      [点我收藏+]

目录管理

例1:  目录的创建/删除

mymkdir.c

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>

#define ERROR(flag)                      if(flag)                    {                            printf("%d: ",__LINE__);            fflush(stdout);                    perror("error");                exit(errno);                }

int main(int argc,char *argv[])
{
    system("ls --color=tty");

    int ret = mkdir("dir", 0777);
    ERROR(ret == -1);

    system("ls --color=tty");

    ret = rmdir("dir");

    system("ls --color=tty");

    return 0;
}

编译/链接/运行, 输出如下:

技术分享

./mymkdir执行中(上图), 三次显示当前目录下的内容. mkdir()执行后到rmdir()执行前有dir目录, rmdir()执行后dir目录被删除

 

例2: 进入另一目录

mychdir.c

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>

#define ERROR(flag)                      if(flag)                    {                            printf("%d: ",__LINE__);            fflush(stdout);                    perror("error");                exit(errno);                }

int main(int argc,char *argv[])
{
    char buf[256];

    char *pret = getcwd(buf,256);
    ERROR(pret == NULL);
    puts(buf);

    int ret = chdir(argv[1]);
    ERROR(ret == -1);
        
    pret = getcwd(buf,256);
    ERROR(pret == NULL);
    puts(buf);
    
    return 0;
}

编译/链接/执行, 输出如下:

技术分享

 

例3: 打开目录, 打印目录内容相关信息

myopendir.c

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <dirent.h>

#define ERROR(flag)                      if(flag)                    {                            printf("%d: ",__LINE__);            fflush(stdout);                    perror("error");                exit(errno);                }

int main(int argc,char *argv[])
{
    DIR *dir;
    struct dirent *p;

    dir = opendir(argv[1]);
    ERROR(dir == NULL);

    while((p = readdir(dir)) != NULL)
    {
        printf("%s  , %d\n", p->d_name, p->d_ino);
    }

    closedir(dir);

    return 0;
}

编译链接执行, 输出结果如下:

技术分享

目录管理

原文:http://www.cnblogs.com/zhanglong71/p/5125496.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!