源码:
//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. */