source: trunk/yat/utility/FileUtil.cc @ 711

Last change on this file since 711 was 711, checked in by Jari Häkkinen, 15 years ago

Fixes #1 and #80. Interface changed.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 2.0 KB
Line 
1// $Id: FileUtil.cc 711 2006-12-21 08:10:30Z jari $
2
3/*
4  Copyright (C) 2004 Jari Häkkinen
5  Copyright (C) 2005 Peter Johansson
6  Copyright (C) 2006 Jari Häkkinen
7
8  This file is part of the yat library, http://lev.thep.lu.se/trac/yat
9
10  The yat library is free software; you can redistribute it and/or
11  modify it under the terms of the GNU General Public License as
12  published by the Free Software Foundation; either version 2 of the
13  License, or (at your option) any later version.
14
15  The yat library is distributed in the hope that it will be useful,
16  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18  General Public License for more details.
19
20  You should have received a copy of the GNU General Public License
21  along with this program; if not, write to the Free Software
22  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
23  02111-1307, USA.
24*/
25
26#include "FileUtil.h"
27
28#include <cerrno>
29#include <iostream>
30#include <string>
31
32#include <sys/stat.h>
33#include <unistd.h>
34
35
36namespace theplu {
37namespace yat {
38namespace utility {
39
40
41  FileUtil::FileUtil(const std::string& path)
42    : path_(path)
43  {
44  }
45
46
47  int FileUtil::permissions(const std::string& bits) const
48  {
49    std::string tryme=path_;
50    if (!exists()) {
51      std::string::size_type pos=path_.find_last_of('/');
52      tryme = ( (pos!=std::string::npos) ? path_.substr(0,pos) : "." );
53    }
54
55    int mode=0;
56    for (u_int i=0; i<bits.length(); i++)
57      switch (bits[i]) {
58          case 'r':
59            mode|=R_OK;
60            break;
61          case 'w':
62            mode|=W_OK;
63            break;
64          case 'x':
65            mode|=X_OK;
66            break;
67      }
68
69    return access(tryme.c_str(),mode);
70  }
71
72
73  bool FileUtil::exists(void) const
74  {
75    struct stat statt;
76    if ( stat(path_.c_str(),&statt) && (errno!=ENOENT) )
77      throw IO_error(std::string("stat(2) call failed with errno: "+errno));
78    return !errno;  // 0 if file exists, non-zero if file does not exist
79  }
80
81
82  const std::string& FileUtil::path(void) const
83  {
84    return path_;
85  }
86
87}}} // of namespace utility, yat, and theplu
Note: See TracBrowser for help on using the repository browser.