slacker と Gilles による 2 つの回答の組み合わせです。lstat を使用しますが、スラッカーが言ったように使用しないでください。dent->d_name だけでなく、フル パスを lstat に送信する必要があります。そして、lstat には sys/stat.h> を含める必要があることを知っている
ように、lstat のマニュアルページを見ると、下部にテストプログラムがあるか、私のものを見てください。
これは、Linuxで「ls」を模倣しようとする私のプログラムです。注: 移植性が心配な場合に備えて、エスケープ シーケンスの色は Windows では機能しません。
#include <iostream>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main(int argc,char* argv[]){
char blue[] = { 0x1b, '[', '1', ';', '3', '4', 'm', 0 };
char normal[]={ 0x1b, '[', '0', ';', '3', '9', 'm', 0 };
char green[]= { 0x1b, '[', '0', ';', '3', '2', 'm', 0 };
char red[]= { 0x1b, '[', '0', ';', '3', '1', 'm', 0 };
char cyan[]= { 0x1b, '[', '0', ';', '3', '6', 'm', 0 };
DIR* myDirectory;
char *path=NULL;
size_t size=100;
int result;
char* fullpath;
if (argc >=3){
std::cout<<"Usage: myls <path>"<<std::endl;
return -1;
}
if (argc >= 2){
myDirectory=opendir(argv[1]);
if (errno==ENOENT){
std::cout<<"error: file does not exist"<<std::endl;
return -1;
}
path=argv[1];
if (path[strlen(path)-1]!='/')
strcat(path,"/");
}
else if(argc==1){
path=getcwd(path,size);
strcat(path,"/");
myDirectory=opendir(path);
}
struct stat fileProperties;
struct dirent* directory;
do{
directory=readdir(myDirectory);
if (directory!=NULL){
fullpath=new char[strlen(path)+strlen(directory->d_name)+2];
strcat(fullpath,path);
strcat(fullpath,directory->d_name);
result=lstat(fullpath,&fileProperties);
//std::cout<<result<<fullpath;
switch (fileProperties.st_mode & S_IFMT){
case S_IFDIR: std::cout<<blue;
break;
case S_IFLNK: std::cout<<cyan; break;
case S_IFREG: std::cout<<normal;
default: std::cout<<normal;
if (fileProperties.st_mode & S_IXUSR)
std::cout<<green;
break;
}
std::cout<<directory->d_name<<"\n";
std::cout<<normal;
}
}while(directory!=NULL);
std::cout<<normal<<'\n';
closedir(myDirectory);
delete[] fullpath;
return 0;
}