Linux/Unix下读取指定目录下的所有文件名

时间:2020-12-26 14:33:57
Linux/Unix下读取指定目录下的所有文件名       调用系统函数opendir()和readdir来实现遍历Linux/Unix下的某个指定目录下的所有文件,并输出文件名。
 实现代码如下:
/*
Author: ACb0y
FileName: main.cpp
Create Time: 2011年8月1日0:41:18
Version: V1.0
*/
#include <iostream>
#include "apue.h"
#include <dirent.h>
using namespace std;

int main(int argc, char * argv[])
{
DIR *dp;
struct dirent *dirp;
if (argc != 2)
{
err_quit("Usage: ls directory_name");
}

//打开指定的目录
if ((dp = opendir(argv[1])) == NULL)
{
err_sys("can't open %s", argv[1]);
}

//遍历目录
while ((dirp = readdir(dp)) != NULL)
{
printf("%s\n", dirp->d_name);
}

//关闭目录
closedir(dp);
return 0;
}