《算法》第一章——打印文件目录结构

转载自:http://blog.csdn.net/nbda1121440/article/details/9120219-------Linux打印文件目录结构

代码:
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>

void printdir(char *dirname,int indent)
{
  DIR *dp;
  struct dirent *entry;
  struct stat statbuf;

  if((dp = opendir(dirname )) == NULL)
  {
    fprintf(err,"open dir %s failed!\n",dirname);
    exit(-1);
  }
  chdir(dirname);//改变当前工作目录
  while((entry = readdir(dp)) != NULL)
  {
    lstat(entry->d_name,&statbuf);
    if(S_ISDIR(statbuf.st_mode))
    {
      if(!strcmp(".",entry->d_name) || !strcmp("..",entry->d_name))
      {
        continue;
      }
      printf("%*s%s\n",indent,"",entry->d_name);
      printdir(entry->d_name,indent+4);
    }
    else
    {
      printf("%*s%s\n",indent,"",entry->d_name);
    }
  }
  chdir("..");
  closedir(dp);
}

int main(void)
{
  printdir("/home",0);
  return 0;
}

体会:
1.关于printf("%*s")的使用。
   *在这里是一个数字占位符,表示字符串宽度。比如:printf("%*s",4)表示printf("%4s")。
   参考:http://blog.csdn.net/patdz/article/details/8256843
2.关于scanf("%*s")的使用。
   表示跳过字符串,不读入。
   参考:http://bbs.csdn.net/topics/390389078

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值