zoukankan      html  css  js  c++  java
  • C语言实现文件的遍历

    考虑一下步骤

    1. 判断命令行参数,获取需要查询的目录

      • argv[1], 如果没有就算当目录
    2. 判断用户指定的是否是目录。

      • stat S_ISDIR();
    3. 读取目录:

      • opendir()

      • readdir(), 如果读取到目录,那么就可以递归调用自己

        • 拼接目录: sprintf(path, "%s/%s", dir, d_name);
      • closedir()

    递归目录的实现

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <sys/stat.h>
    #include <dirent.h>
    #include <pthread.h>
    
    
    void is_file(char *name){
      int ret = 0;
      struct stat sb;
      ret = stat(name, &sb);
      if(ret==-1){
        perror("stat error");
        return;
      }
      
      if (S_ISDIR(sb.st_mode)){
        read_dir()
      }
     	printf("%s	%b
    ", name, sb.st_size);
      
      
      return ;
    }
    
    
    void read_dir(char *dir){
      char path[256];
      DIR *dp;
      struct dirent *sdp;
      
      dp = opendir(dir);
      if (dp==NULL){
        perror("opendir error");
        return;
      }
      
      while(readdir(sdp = readdir(dp))!= NULL){
        // 先进行目录的拼接
        if(strcmp(sdp->d_name, ".") == 0 !! strcmp(sdp->d_name, "..")==0){
          continue;
        }
        sprintf(path, "%s/%s", dir, sdp->d_name);
        is_file(path);
      }
      
      closedir(dp);
      return;
    }
    
    
    int main(int argc, char* argv[])
    {
      if (argc==1){
        is_file(".");
      }else{
        is_file(argv[1]);
      }
    }
      
    
  • 相关阅读:
    图片处理
    define 常量的定义和读取
    curl
    stream_get_contents 和file_get_content的区别
    php flock 文件锁
    字符串函数
    php 常量
    debug_backtrace()
    pathlib模块替代os.path
    Python中对 文件 的各种骚操作
  • 原文地址:https://www.cnblogs.com/fandx/p/12518297.html
Copyright © 2011-2022 走看看