頭文件dirent.h

<dirent.h>是POSIX.1標準定義的unix類目錄操做的頭文件,包含了許多UNIX系統服務的函數原型,例如opendir函數、readdir函數。函數

opendir函數:
 
DIR *opendir(const char *pathname);返回值:若成功則返回 指針,若出錯則返回NULL。
struct dirent *readdir(DIR *dp); 返回值:若成功則返回指針,若在目錄結尾或出錯則返回NULL。
 
命令
列出一個目錄下全部文件的名字,簡要實現unix下ls命令
#include<stdio.h>
#include<dirent.h>
 
int main(int argc,char* agrv[]){
DIR* dp;
struct dirent* dirp;
 
if(argc!=2){
  printf("usage:lsdirectory_name\n");
  //不返回的話,程序會執行出錯
  return 0;
}
if((dp=opendir(agrv[1]))==NULL){
  printf("cannotopen%s",agrv[1]);
  //不返回的話,程序會執行出錯
  return 0;
}
while((dirp=readdir(dp))!=NULL){
  printf("%s\n",dirp->d_name);
}
closedir(dp);
//c語言以非0爲真,因此程序執行成功的話返回1,執行失敗返回0
return 1;
}
相關文章
相關標籤/搜索