歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux教程

Linux/Unix下讀取指定目錄下的所有文件名

調用系統函數opendir()和readdir來實現遍歷Linux/Unix下的某個指定目錄下的所有文件,並輸出文件名。

實現代碼如下:

  1. /* 
  2.     Author: ACb0y 
  3.     FileName: main.cpp 
  4.     Create Time: 2011年8月1日0:41:18 
  5.     Version: V1.0 
  6.     www.linuxidc.com
  7.  */  
  8. #include <iostream>   
  9. #include "apue.h"   
  10. #include <dirent.h>   
  11. using namespace std;  
  12.   
  13. int main(int argc, char * argv[])  
  14. {  
  15.     DIR *dp;  
  16.     struct dirent *dirp;  
  17.     if (argc != 2)   
  18.     {  
  19.         err_quit("Usage: ls directory_name");  
  20.     }  
  21.       
  22.     //打開指定的目錄   
  23.     if ((dp = opendir(argv[1])) == NULL)  
  24.     {  
  25.         err_sys("can't open %s", argv[1]);  
  26.     }  
  27.       
  28.     //遍歷目錄   
  29.     while ((dirp = readdir(dp)) != NULL)  
  30.     {  
  31.         printf("%s\n", dirp->d_name);  
  32.     }  
  33.       
  34.     //關閉目錄   
  35.     closedir(dp);  
  36.     return 0;  
  37. }  
Copyright © Linux教程網 All Rights Reserved