Linux下对文件和字符串的操作

来源:互联网 发布:科比历届总决赛数据 编辑:程序博客网 时间:2024/05/16 17:56

//文件信息结构体

struct FILE_INFO
{
 enum FILE_TYPE{file,dir,other};
 std::string m_name;
 FILE_TYPE m_ft;
 off_t m_size;
 time_t m_mtime;
}

 

//搜集指定目录下文件的信息
bool list_file(const char *name,std::vector<FILE_iNFO>&fis,bool onlydir)
{
 DIR *dir;
 dirent *de;
 std::string file_name;
 FILE_INFO fi;
 struct stat fs;
 tassert(name!=NULL);
 dir=opendir(name);
 if(dir=NULL)
 fis.clear();
 while((de=readdir(dir))!=NULL)
 {
  if(strcmp(de->d_name,".")==0||strcmp(de->d_name,"..")==0)
   continue;
  file_name=name;
  file_name+="/";
  file_name+=de->d_name;
  if(stat(file_name.c_str(),&fs)!=0)
   continue;
  fi.m_name=de->d_name;
  if(onlydir&&S_ISDIR(fs.st_mode))
  {
   fi.m_ft=FILE_INFO::dir;
   fi.m_size=fs.st_size;
   fi.m_mtime=fs.st_mtime;
   fis.push_back(fi);
  }
  else if(false==onlydir)
  {
   if(S_ISREG(fs.st_mode))
    fi.m_ft=FILE_INFO::file;
   else if (S_ISDIR(fs.st_mode))
    fi.m_ft=FILE_INFO::dir;
   else
    fi.m_ft=FILE_INFO::other
   fi.m_siez=fs.st_size;
   fi.m_mtime=fs.st_mtime;
   fis.push_back(fi);
  }
 }
 closedir(dir);
}

 

//删除文件

bool remove_file(const char *name)
{
 std::vector<FILE_INFO>fis;
 std::string next;
 tassert(name!=NULL)
 list_file(name,fis,false);
 for(size_t i=0;i<fis.size();i++)
 {
  next=name;
  next+="/";
  next+=fis[i].m_name;
  remove_file(next,c_str());
 }
 unlink(name);
 rmdir(name);
 return true;
}

 

//创建目录

bool make_dir(const char *path)
{
 std::vector<std::string> arr;
 std::string name;
 std::string tmp;
 struct stat fst;
 if(strlen(path)<=1)
  return false;
 if(path[0]=='/')
 {
  name="/"
  tmp=path+1;
 }
 else
 {
  tmp=path;
 }
 split(tmp,"/",arr);
 for(size_t i=0;i<arr.size();i++,name+="/")
 {
  name+=arr[i];
  if(access(name.c_str(),F_OK)!=0)
  {
   if(mkdir(name.c_str(),0755)!=0)
    return false;
  }
 }
 if(access(path,F_OK)!=0)
  return false;
 if(stat(path,&fst)!=0)
  return false;
 if(!S_ISDIR(fst.st_mode))
  return false;
 return true;
}

 

//把一个字符串按指定的分隔符进行分隔

bool split(std::string&str,std::string sep,std::vector<std::string>&res)
{
 std::string::size_type pos1;
 std::string::size_type pos2;
 tassert(sep.size()>0);
 if(sep.size()<=0)
  return false;
 res.clear();
 for(pos1=0;pos1<str.size();)
 {
  pos2=str.find(sep,pos1);
  if(pos2<pos1||pos2==std::string::npos)
   break;
  res.push_back(str.substr(pos1,pos2-pos1));
  pos1=pos2+sep.size();
 }
 res.push_back(str.substr(pos1));
 return true;
}

 

//去除字符串前后的空格

void trim(std::string&str)
{
 std::string::size_type pos1;
 std::string::size_type pos2;
 pos1=0;
 pos2=str.size();
 for(;pos1<pos2&&isspace(str[pos1]),pos1++)
 {
 }
 for(;pos2?pos1&&isspace(str[pos2-1],pos2--))
 {
 }
 str=str.substr(pos1,pos2-pos1);
}