Ignore:
Timestamp:
Dec 15, 2012, 7:29:55 AM (9 years ago)
Author:
Peter
Message:

New functions chdir, chmod, copy_file, fnmatch, remove, rename, and replace
refs #717

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/yat/utility/utility.cc

    r2892 r2906  
    2626#include "utility.h"
    2727
     28#include "Exception.h"
    2829#include "FileUtil.h"
    2930#include "stl_utility.h"
    3031
     32#include <fnmatch.h>
     33#include <fstream>
    3134#include <sstream>
    3235#include <string>
     
    5053
    5154
     55  void chdir(const std::string& dir)
     56  {
     57    if (::chdir(dir.c_str()) )
     58      throw errno_error("chdir: " + dir + ":");
     59  }
     60
     61
     62  void chmod(const std::string& filename, mode_t mode)
     63  {
     64    if (::chmod(filename.c_str(), mode))
     65      throw errno_error("chmod: ");
     66  }
     67
     68
     69  void copy_file(const std::string& source, const std::string& target)
     70  {
     71    std::ifstream is;
     72    std::ofstream os;
     73
     74    is.open(source.c_str(), std::ios::in | std::ios::binary);
     75    os.open(target.c_str(), std::ios::out | std::ios::binary);
     76    os << is.rdbuf();
     77    if (!os.good()) {
     78      std::ostringstream ss;
     79      ss << "copy_file failed writing to '" << target << "'\n";
     80      throw runtime_error(ss.str());
     81    }
     82    if (is.bad() || is.fail()) {
     83      std::ostringstream ss;
     84      ss << "copy_file failed reading from '" << source << "'\n";
     85      throw runtime_error(ss.str());
     86    }
     87    is.close();
     88    os.close();
     89
     90    // copy permissions
     91    struct stat nodestat;
     92    stat(source.c_str(), &nodestat);
     93    chmod(target.c_str(), nodestat.st_mode);
     94  }
     95
     96
    5297  std::string dirname(const std::string& path)
    5398  {
     
    65110      return "/";
    66111    return path.substr(0,pos);
     112  }
     113
     114
     115  bool fnmatch(const std::string& pattern, const std::string& str)
     116  {
     117    int res = ::fnmatch(pattern.c_str(), str.c_str(), 0);
     118    if (res==0)
     119      return true;
     120    if (res!=FNM_NOMATCH) {
     121      std::stringstream ss;
     122      ss << "fnmatch(" << pattern << ", " << str << ")";
     123      throw runtime_error(ss.str());
     124    }
     125    return false;
    67126  }
    68127
Note: See TracChangeset for help on using the changeset viewer.