1 /* Check file
2
3 * Copyright (C) 1998 J.A. Bezemer
4 *
5 * Licensed under the terms of the GNU General Public License.
6 * ABSOLUTELY NO WARRANTY.
7 * See the file `COPYING' in this directory.
8 */
9
10
11 #include "checkfile.h"
12 #include <sys/stat.h>
13 #include <string.h>
14
15
16 /* ---- From GNU shellutils, lib/stripslash.h: */
17
18 /* Remove trailing slashes from PATH.
19 This is useful when using filename completion from a shell that
20 adds a "/" after directory names (such as tcsh and bash), because
21 the Unix rename and rmdir system calls return an "Invalid argument" error
22 when given a path that ends in "/" (except for the root directory). */
23
24 void
strip_trailing_slashes(char * path)25 strip_trailing_slashes (char *path)
26 {
27 int last;
28
29 last = strlen (path) - 1;
30 while (last > 0 && path[last] == '/')
31 path[last--] = '\0';
32 }
33 /* ---- End */
34
35 int
checkfile(char * filename)36 checkfile (char *filename)
37 {
38 struct stat buf;
39 int i;
40 char myfilename[250];
41 char *slash;
42
43 strip_trailing_slashes (filename);
44
45 i = stat (filename, &buf);
46
47 if (!i) /* file or dir found */
48 {
49 if (S_ISDIR (buf.st_mode))
50 {
51 if (strcmp (filename, "/"))
52 strcat (filename, "/");
53 return DIR_EXISTS;
54 }
55 else
56 return FILE_EXISTS;
57 }
58 else
59 /* file does not exist, check dir */
60 {
61 strcpy (myfilename, filename);
62
63 /* ---- Adapted from GNU shellutils, src/dirname.c: */
64
65 slash = strrchr (myfilename, '/');
66 if (slash == NULL)
67 strcpy (myfilename, ".");
68 else
69 {
70 /* Remove any trailing slashes and final element. */
71 while (slash > myfilename && *slash == '/')
72 --slash;
73 slash[1] = 0;
74 }
75
76 /* ---- End */
77
78 i = stat (myfilename, &buf);
79 if (!i) /* dir found */
80 {
81 if (S_ISDIR (buf.st_mode))
82 return DIR_OK_NEW_FILE;
83
84 return DIR_WRONG;
85 }
86 else /* dir does not exist */
87 return DIR_WRONG;
88
89 } /* else: file not found */
90 }
91