源码:
//ListRegularFile.cpp 显示普通文件
#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <assert.h>
#include <string.h>
#ifdef _WIN32
#define FLAG_FILE _S_IFREG
#else
#define FLAG_FILE __S_IFREG
#endif
int main(int argc, char *argv[])
{
if (2 != argc)
{
printf("Usage: ListFile SourceFolder\n");
return 1;
}
DIR* pDir = NULL;
struct dirent* ent = NULL;
pDir = opendir(argv[1]);
if (NULL == pDir)
{
printf("Source dir not exists!");
return 1;
}
int nFolderLength = strlen(argv[1]);
const int FILE_LENGTH = 1024;
char FilePath[FILE_LENGTH];
assert(nFolderLength<FILE_LENGTH);
strncpy(FilePath, argv[1], nFolderLength);
FilePath[nFolderLength] = '\0';
int nFileNameLength;
struct stat stFileInfo;
while (NULL != (ent=readdir(pDir)))
{
//Copy File Name
nFileNameLength = strlen(ent->d_name);
assert(nFileNameLength + nFolderLength < FILE_LENGTH);
strncpy(&FilePath[nFolderLength], ent->d_name, nFileNameLength);
FilePath[nFolderLength + nFileNameLength] = '\0';
//Check if is a file
if (0 != stat(FilePath, &stFileInfo))
{
printf("\tGet file info failed!\n");
continue;
}
if (stFileInfo.st_mode & FLAG_FILE)
{
printf("%s\n", ent->d_name);
}
}
closedir(pDir);
pDir = NULL;
ent = NULL;
return 1;
}
编译:
g++ -o ListRegularFile ListRegularFile.cpp
本程序也可以在WINDOWS下编译执行:g++ -o ListRegularFile.exe ListRegularFile.cpp
测试:
ListRegularFile ../
说明:
1、看#ifdef _WIN32处,WINDOWS下一些宏的定义和LINUX下不同
2、关于文件类型的定义,Linux下在<bits/stat.h>中,如下:
/* File types. */
#define __S_IFDIR 0040000 /* Directory. */
#define __S_IFCHR 0020000 /* Character device. */
#define __S_IFBLK 0060000 /* Block device. */
#define __S_IFREG 0100000 /* Regular file. */
#define __S_IFIFO 0010000 /* FIFO. */
#define __S_IFLNK 0120000 /* Symbolic link. */
#define __S_IFSOCK 0140000 /* Socket. */
分享到:
相关推荐
linux运维学习笔记:MySQL多实例配置实战
linux基础知识学习,可以方便新手快速入门linux系统
linux运维笔记:分布式文件系统GlusterFS.docx
linux运维学习笔记:Shell变量
学习linux的一些笔记,提交到csdn,相互学习交流
linux运维学习笔记:Shell脚本调试
linux运维学习笔记:Shell变量的数值运算
linux运维学习笔记:数据库介绍与安装管理
学习linux的一些笔记,提交到csdn,相互学习交流
【linux学习笔记--17】POSIX IPC——消息队列.doc 【linux学习笔记--18】POSIX IPC——信号量.doc 【linux学习笔记--19】POSIX IPC——共享内存.doc ...【linux学习笔记-6】文件IO操作--读写、重定向等.
linux运维学习笔记:Shell前言
linux运维学习笔记:Shell函数
linux运维学习笔记:Mysql日志
linux运维学习笔记:Shell脚本书写规范
Linux学习笔记
linux运维学习笔记:Shell条件语句
超详细linux学习笔记,【网络安全技术】,分享给大家。
Linux学习笔记包含LINUX常用命令、磁盘管理、用户管理、文件权限、目录结构、软件安装等内容,适用于Linux初学者学习以及高水平者查遗补漏
linux运维学习笔记:Mysql备份与恢复
linux运维学习笔记:企业Shell面试题总结-2