zoukankan      html  css  js  c++  java
  • 文件、目录操作相关函数

    一。文件操作函数

    1.stat函数

    1.1 stat记录了文件的信息

    1.2 st_mode由16位二进制数组成,如下图:

    下图表示各种文件类型对应的8进制数,将st_mode&0170000可以得到文件类型,若要判断一个文件是不是普通文件:

    struct stat st;

    stat("123.txt",&st);

    if((st.st_mode&S_IFMT)==S_IFREG)

    {

    printf(“这是普通文件”);

    }

     1.3计算文件的权限类型如下图:

     另外可以参考:https://blog.csdn.net/astrotycoon/article/details/8679676

    2.lstat函数

    3.chmod

    4.chown

    uid和gid在vi /etc/passwd中可以查看

    5.truncate

    6.link

    7.rename

    8.dup dup2 

    用来复制文件描述符 

    函数原型:

    1.dup将oldfd复制为最小可用的文件描述符,并返回

    示例程序:通过fd和ret文件描述符都可以往文件a.txt中写数据,并且文件指针不会还原。

    2.dup2将oldfd复制为newfd

    示例程序:将原本“english.txt”的文件描述符fd复制为fd1,即a.txt的文件描述符,并往a.txt中写数据

    9.fcntl

    cmd传入F_GETFL时获取文件状态,arg=0;

    cmd传入F_SETFL时设置文件状态,arg=flag;

    二.目录操作函数

    1.chdir 和 getcwd 

    2.mkdir 和 rmdir 

    3.opendir

    4.readdir

    //递归读取子目录并计算普通文件个数
    #include<stdio.h> #include<stdlib.h> #include<dirent> int getFileNum(const char *filename) { DIR *dir=NULL; dir=opendir(filename); struct dirent* ptr=NULL; if(dir==NULL) { perror("opendir"); exit(1); } char path[1024]={0}; while((ptr=readdir(dir))!=null) { //过滤.和.. if(strcmp(ptr->d_name,".")==0||strcmp(ptr->d_name,"..")==0) { continue; } //如果是目录 if(ptr->d_type==DT_DIR) { sprintf(path,"%s%s",filename,ptr->d_name); //递归读目录 total+=getFileNum(path); } //如果是普通文件 if(ptr->d_type==DT_REG) { total++; } } closedir(dir); return total; } int main(int argc,char* argv[]) { int total=getFileNum(argv[1]); printf("%s has file numbers %d",argv[1],total); return 0; }

      

    5.closedir

  • 相关阅读:
    电脑hosts文件、hosts文件说明、hosts文件域名和ip
    java复制对象属性值、复制值
    查找替换、idea全局搜索、全局替换、全局搜索替换
    谷歌浏览器问题、
    http请求类、RestTemplate、请求工具类
    easypoi导入
    vue下载本地文件、vue下载本地文件报错、vue下载本地文件找不到
    arm汇编指令的条件码
    GNU内嵌汇编
    shell脚本错误:syntax error near unexpected token '$' ''
  • 原文地址:https://www.cnblogs.com/sclu/p/11246003.html
Copyright © 2011-2022 走看看