int ls(std::string path,std::string& ret)标签:std,name,C++,ret,ss,ls,file,linux,dir From: https://blog.51cto.com/yetaotao/5796925
{
DIR* dirp= opendir(path.c_str());
if(!dirp)
{
return -1;
}
struct stat st;
struct dirent *dir;
std::vector<:string> file_name;
std::vector<:string> dir_name;
while((dir=readdir(dirp)) != NULL)
{
if(strcmp(dir->d_name,".")==0 ||
strcmp(dir->d_name,"..")==0)
{
continue;
}
std::string full_path=path + dir->d_name;
if(lstat(full_path.c_str(),&st)==-1)
{
continue;
}
std::string name=dir->d_name;
//replace the blank char in name with "%$".
while(name.find(" ") !=std::string::npos)
{
name.replace(name.find(" "),1,"$%");
}
if(S_ISDIR(st.st_mode)) //S_ISDIR()崎登僅頁倦頁朕村猟周
{
name +="[d]";
dir_name.push_back(name);
}
else
{
file_name.push_back(name);
}
}
closedir(dirp);
sort(file_name.begin(),file_name.end());
sort(dir_name.begin(),dir_name.end());
std::stringstream ss_ret;
int count=0;
for(auto i=dir_name.begin();i!=dir_name.end();i++)
{
ss_ret<
count++;
if(count%5==0)
{
ss_ret<<:endl>
}
else
{
ss_ret<
}
}
for(auto i=file_name.begin();i!=file_name.end();i++)
{
ss_ret<
count++;
if(count%5==0) //耽励倖兆忖指概。
{
ss_ret<<:endl>
}
else
{
ss_ret<
}
}
ret = ss_ret.str();
return 0;
}