《算法》第一章——打印文件目錄結構

轉載自: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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章