c语言系统函数——目录操作

一、 文件夹的系统函数
    1.mkdir(),创建一个目录文件。
    int mkdir(const char *pathname, mode_t mode);
    第一个参数是路径,第二个参数是权限,一般为0777.
    在shell命令中,使用mkdir可以创建一个目录,如果使用mkdir aa/bb/cc创建目录,而aa不存在时,可以使用mkdir aa/bb/cc -p;
    如果使用mkdir函数来创建,需要一个一个的创建。
    
    2.access()检查是否具有某些权限,是否存在,是否有读写运行的权限等。
     int access(const char *pathname, int mode);
    返回:如果具有这个权限返回0,没有或者异常返回-1.
    
    3.opendir(),打开一个目录文件
       DIR *opendir(const char *name);
       DIR *fdopendir(int fd);
      函数返回一个DIR的指针。
      
    4.readdir();读取目录下面的文件
      struct dirent *readdir(DIR *dirp);
     返回的结果是一个结构体。
      struct dirent {
               ino_t          d_ino;       /* inode 编号 */
               off_t          d_off;       /* offset to the next dirent */
               unsigned short d_reclen;    /* length of this record */
               unsigned char  d_type;      /* type of file; not supported
                                              by all file system types */
               char           d_name[256]; /* 文件名称*/
           };
      其中文件的类型有:1.DT_REG普通文件      2.DT_LIK符号链接      3.DT_DIR目录文件     4.DT_FIFO管道文件
      如果返回NULL说明遍历完了。
      
  例题:

    1.使用系统调用完成mkdir实现建立xx/yy/zz

    2.完成命令ls

    3.完成文件夹的复制

 

一 、mkdir的实现。

#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>

//仿写mkdir命令
//输入的如果是x/y/z;而x并不存在,就会一个一个的创建
//核心是分割字符串

int main(int argc,char *argv[])
{
    argv[1];
    //对argv[1]进行分割
    char * p =  strtok(argv[1],"/");
    int erro = 0;
    char * path = (char *)malloc(256);
    strcpy(path,p);
    printf("%s\n",path);
    if(access(path,F_OK) != 0)
    {
        erro = mkdir(path ,0777);
        if(erro == -1)
        {
            perror("mkdir");
            return -1;
        }
    }
    while(
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值