更新日が古いダミーファイルを作るプログラム

30分プログラム、その731。更新日(mtime)が古いダミーファイルを作ってみました。
動機は、

  • 一月以上前のファイルだけを消すシェルクスクリプトを書きたい
  • いきなり本番環境じゃ動かせない
  • ダミーファイルを作ろう

という感じです。

作ってる途中でtouchコマンドの-tで更新時刻を設定できることに気がつきました。これで十分だよなぁ、と思いつつも、最後まで作っちゃいました。
まあ、Boostを使うのは楽しいのでよしとしましょう。

使い方

$ g++ -I/opt/local/include -Wall mk-old-times.cxx
$ ./a.out 3
$ ls -l dummy-file-*
-r-x------   1 mzp      staff       0  2  6 22:08 dummy-file-0
--wxr-----   1 mzp      staff       0  2  5 22:08 dummy-file-1
--w-------   1 mzp      staff       0  2  4 22:08 dummy-file-2

ソースコード

// g++ -I/opt/local/include -Wall mk-old-times.cxx
#include <sys/time.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <iostream>
#include <string>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>

void touch(const std::string &path, time_t t){
  const timeval ts[2] = { { t ,0},
			  { t ,0}};
  const int fd = open(path.c_str(), O_CREAT | O_WRONLY);
  if(futimes(fd, ts)){
    std::cerr << strerror(errno) << std::endl;
  }
  close(fd);
}

int main(int argc, char *argv[])
{
  using namespace std;
  using boost::lexical_cast;

  if(argc < 2){
    cout << "usage : " << argv[0] << " [count]\n";
    exit(0);
  }
  int n = lexical_cast<int>(argv[1]);
  int now = time(NULL);

  for (int i = 0; i < n; ++i)
  {
    boost::format s = boost::format("dummy-file-%1%") % i;
    cout << s << endl;
    touch( s.str(), now - i * 24*60*60);
  }
  return 0;
}