zoukankan      html  css  js  c++  java
  • Linux 文件管理(C语言库函数三)

    找到当前目录
    char *getcwd(char * buf,size_t size)
    getcwd函数把当前工作目录的绝对路径名复制到buf中,size指示buf的大小
    如果buf不够大,不能装下整个路径名,getcwd返回NULL。
    当前目录是指当前页面所在的目录,不是指程序所在的目录,相当于"pwd"命令
    //getcwd()
    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <string.h>
    #include <errno.h>
    
    int main(int arg, char * args[])
    {
        //获取当前目录
        char buf[256]={0};
        /*
          getcwd()函数头文件是unistd.h
         */
        char *res=getcwd(buf,sizeof(buf));
        if(res)
        {
            printf("%s
    ",buf);
        }
        return 0;
    }
    获取目录列表
    --用opendir函数打开目录文件
    --用readdir函数读出目录文件内容
    --用closedir函数关闭目录文件。
    --这些函数都在<dirent.h>头文件中声明
    DIR *opendir(const char *name);
    struct dirent *readdir(DIR *dirp);
    int closedir(DIR *dirp);
    opendir函数打开pathname指向的目录文件,如果错误返回NULL
    创建目录--暂时只能手动创建,我还没有好办法
    struct dirent {
                   ino_t          d_ino;       /* inode number */
                   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]; /* filename */
               };
    //opendir(),readdir(),closedir()
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <errno.h>
    #include <sys/types.h>
    #include <dirent.h>
    
    int main(int arg, char * args[])
    {
        if(arg<2)
        {
            printf("请输入一个参数!
    ");
            return 0;
        }
        //创建一个目录指针
        DIR *dp=NULL;
        //定义目录结构指针
        struct dirent *drp=NULL;
        //打开一个目录
        dp=opendir(args[1]);
        if(dp==NULL)
        {
            printf("error msg:%s
    ",strerror(errno));
            return 0;
        }
        /*
          drp=readdir(dp)这是赋值操作
          while判断是drp对象是否为空
          readdir(dp)读出目录文件内容,返回值是struct dirent结构体对象指针
         */
        while((drp=readdir(dp))!=NULL)
        {
            //注意:struct dirent在windows和Linux下的定义不同
            printf("%s
    ",drp->d_name);
        }
        //关闭目录指针
        if(dp!=NULL)
            closedir(dp);
        return 0;
    }
  • 相关阅读:
    1613. 最高频率的IP
    JavaMap常用操作
    centos虚拟机 与主机同步时间
    Kubernetes prometheus+grafana k8s 监控
    k8s集群搭建 2019
    linux运维/自动化开发__目录
    mysql DBA 指南
    mysql 监控
    微信公众号实现zaabix报警2017脚本(升级企业微信后)
    分布式监控开发 05 历史数据存储
  • 原文地址:https://www.cnblogs.com/zhanggaofeng/p/5800689.html
Copyright © 2011-2022 走看看