Welcome 微信登录

首页 / 操作系统 / 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 ", dirp->d_name);  
  32.     }  
  33.       
  34.     //关闭目录   
  35.     closedir(dp);  
  36.     return 0;  
  37. }  
Linux系统增加交换空间的方法编写Shell脚本查看Linux当前各用户的cpu和memory消耗比例相关资讯      Linux教程 
  • Linux教程:如何在命令行中查看目  (07/28/2014 12:22:23)
  • Linux 修改root密码  (11/03/2012 07:53:38)
  • su - root 与su root的区别  (06/06/2012 00:39:40)
  • Linux进程间通信:消息队列  (01/28/2013 09:43:00)
  • U盘安装Linux开机无法启动解决方法  (10/07/2012 08:55:52)
  • Windows 7/Linux 同步时间  (05/15/2012 06:17:55)
本文评论 查看全部评论 (0)
表情: 姓名: 字数