]> Creatis software - CreaPhase.git/blob - octave_packages/io-1.0.19/fexist.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / io-1.0.19 / fexist.m
1 ## Copyright (C) 2008 Jaroslav Hajek <highegg@gmail.com>
2 ##
3 ## This program is free software; you can redistribute it and/or modify it under
4 ## the terms of the GNU General Public License as published by the Free Software
5 ## Foundation; either version 3 of the License, or (at your option) any later
6 ## version.
7 ##
8 ## This program is distributed in the hope that it will be useful, but WITHOUT
9 ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
11 ## details.
12 ##
13 ## You should have received a copy of the GNU General Public License along with
14 ## this program; if not, see <http://www.gnu.org/licenses/>.
15
16 ## -*- texinfo -*-
17 ## @deftypefn{Function File} ex = fexist (file, tspec, aspec)
18 ## Checks whether a file exists.
19 ## @var{file} is the queried file path.
20 ## @var{tspec} is a combination of letters f,d,p,S, corresponding
21 ## to file types:
22 ## @itemize
23 ## @item f: regular file
24 ## @item d: directory
25 ## @item p: named pipe (FIFO special file)
26 ## @item S: socket
27 ## @end itemize
28 ##
29 ## The query is true if the actual file type matches any of 
30 ## the specified options.
31 ##
32 ## @var{aspec} is a combination of letters r,w,x, corresponding
33 ## to queried access privileges to the file. The query is true
34 ## if the current user has all the spefied types of access, either
35 ## through "user", "group" or "other" specs.
36 ##
37 ## @seealso{stat, lstat}
38 ## @end deftypefn
39
40 function ex = fexist (file, tspec, aspec)
41 s = stat (file);
42 if (isempty (s))
43   ex = 0;
44 else
45   ex = 1;
46   if (nargin >= 2 && ! isempty (tspec))
47     ft = 0;
48     for c = tspec
49       switch (c)
50       case 'f'
51         ft |= S_ISREG (s.mode);
52       case 'd'
53         ft |= S_ISDIR (s.mode);
54       case 'p'
55         ft |= S_ISFIFO (s.mode);
56       case 'S'
57         ft |= S_ISSOCK (s.mode);
58       otherwise
59         error ("invalid file type spec: %s", c)
60       endswitch
61     endfor
62     ex &= ft;
63   endif
64   if (ex && nargin >= 3 && ! isempty (aspec))
65     at = 1;
66     mypid = (s.uid == getuid ());
67     mygid = (s.gid == getgid ());
68     mstr = s.modestr(2:end);
69     for c = aspec
70       switch (c)
71       case 'r'
72         at &= (mypid && mstr(1) == c) || (mygid && mstr(4) == c) || mstr(7) == c;
73       case 'w'
74         at &= (mypid && mstr(2) == c) || (mygid && mstr(5) == c) || mstr(8) == c;
75       case 'x'
76         at &= (mypid && mstr(3) == c) || (mygid && mstr(6) == c) || mstr(9) == c;
77       otherwise
78         error ("invalid access type spec: %s", c)
79       endswitch
80     endfor
81     ex &= at;
82   endif
83 endif