lilypond-1.3.100
[lilypond.git] / flower / file-path.cc
blob80c34db4c1701eb9e7dec6dbe065cdece72e9688
1 /*
2 path.cc - manipulation of paths and filenames.
3 */
5 #include "config.h"
6 #include <stdio.h>
7 #include <errno.h>
8 #if HAVE_SYS_STAT_H
9 #include <sys/stat.h>
10 #endif
12 #include "file-path.hh"
13 #include "flower-debug.hh"
15 #ifndef DIRSEP
16 #define DIRSEP '/'
17 #endif
19 #ifndef PATHSEP
20 #define PATHSEP ':'
21 #endif
23 /**
24 @param path the original full filename
25 @return 4 components of the path. They can be empty
27 void
28 split_path (String path,
29 String &drive, String &dirs, String &filebase, String &extension)
31 // peel off components, one by one.
32 int di = path.index_i (':');
33 if (di >= 0)
35 drive = path.left_str (di + 1);
36 path = path.right_str (path.length_i () - di -1);
38 else
39 drive = "";
41 di = path.index_last_i (DIRSEP);
42 if (di >=0)
44 dirs = path.left_str (di + 1);
45 path = path.right_str (path.length_i ()-di -1);
47 else
48 dirs = "";
50 di = path.index_last_i ('.');
51 if (di >= 0)
53 filebase = path.left_str (di);
54 extension =path.right_str (path.length_i ()-di);
56 else
58 extension = "";
59 filebase = path;
63 void
64 File_path::parse_path (String p)
66 int l;
68 while ( (l = p.length_i ()) )
70 int i = p.index_i(PATHSEP);
71 if (i <0)
72 i = l;
73 add (p.left_str(i));
74 p = p.right_str (l- i - 1);
81 /** Find a file.
82 It will search in the current dir, in the construction-arg, and
83 in any other added path, in this order.
85 @return
86 The full path if found, or empty string if not found
88 String
89 File_path::find (String nm) const
91 DEBUG_OUT << "looking for" << nm << ": ";
92 if (!nm.length_i() || (nm == "-") )
93 return nm;
94 for (int i=0; i < size(); i++)
96 String path = elem(i);
97 String sep = to_str (DIRSEP);
98 String right(path.right_str (1));
99 if (path.length_i () && right != sep)
100 path += to_str (DIRSEP);
102 path += nm;
104 DEBUG_OUT << path << "? ";
106 #if 0
108 Check if directory. TODO: encapsulate for autoconf
110 struct stat sbuf;
111 if (stat (path.ch_C(), &sbuf) == ENOENT)
112 continue;
114 if (!(sbuf.st_mode & __S_IFREG))
115 continue;
116 #endif
117 #if !STAT_MACROS_BROKEN
118 struct stat sbuf;
119 if (stat (path.ch_C (), &sbuf) == ENOENT)
120 continue;
122 if (S_ISDIR (sbuf.st_mode))
123 continue;
124 #endif
126 FILE *f = fopen (path.ch_C(), "r"); // ugh!
127 if (f)
129 DEBUG_OUT << "found\n";
130 fclose (f);
131 return path;
134 DEBUG_OUT << '\n';
135 return "";
139 Add a directory, return false if failed
141 bool
142 File_path::try_add (String s)
144 if (s == "")
145 s = ".";
146 FILE * f = fopen (s.ch_C(), "r");
147 if (!f)
148 return false;
149 fclose (f);
151 push (s);
152 return true;
155 void
156 File_path::add (String s)
158 push (s);
161 String
162 File_path::str () const
164 String s;
165 for (int i=0; i< size (); i++)
167 s = s + elem (i);
168 if (i < size () -1 )
169 s += ":";
171 return s;