4 #include <msp/core/systemerror.h>
5 #include <msp/strings/regex.h>
6 #include <msp/strings/utils.h>
20 /** Helper function to determine the location of the program's executable.
21 Caches the last result to cut down filesystem access with repeated calls. */
22 const Path &get_bin_dir(const string &argv0)
24 static string last_argv0;
27 if(!(argv0==last_argv0))
30 if(argv0.find('/')==string::npos)
32 const char *path = getenv("PATH");
33 vector<string> dirs = split(path, ':');
34 for(vector<string>::const_iterator i=dirs.begin(); i!=dirs.end(); ++i)
35 if(exists(Path(*i)/argv0))
37 exe = realpath(Path(*i)/argv0);
42 exe = realpath(argv0);
45 bin_dir = dirname(exe);
54 not_a_directory::not_a_directory(const Path &p):
55 runtime_error(p.str())
59 void mkpath(const Path &path, int mode)
62 for(Path::Iterator i=path.begin(); i!=path.end(); ++i)
66 if(p.size()==1 && p.is_absolute())
69 if(FS::Stat st = stat(p))
71 if(!st.is_directory())
72 throw not_a_directory(p);
80 void rmpath(const Path &path)
82 list<string> files = list_files(path);
83 for(list<string>::iterator i=files.begin(); i!=files.end(); ++i)
95 list<string> list_files(const Path &path)
97 return list_filtered(path, string());
100 list<string> list_filtered(const Path &path, const string &filter)
102 Regex r_filter(filter);
105 DIR *dir = opendir(path.str().c_str());
108 while(dirent *de = readdir(dir))
110 const char *fn = de->d_name;
111 if(fn[0]=='.' && (fn[1]==0 || (fn[1]=='.' && fn[2]==0)))
113 if(r_filter.match(fn))
114 result.push_back(fn);
125 return ::getcwd(buf, sizeof(buf));
128 Path get_sys_conf_dir(const string &argv0)
130 Path dir = get_bin_dir(argv0);
132 if(dir[-1]=="bin" || dir[-1]=="sbin")
143 Path get_sys_data_dir(const string &argv0, const string &appname)
145 Path dir = get_bin_dir(argv0);
147 if(dir[-1]=="bin" || dir[-1]=="sbin")
148 return dir/".."/"share"/appname;
153 Path get_sys_lib_dir(const string &argv0, const string &appname)
155 Path dir = get_bin_dir(argv0);
157 if(dir[-1]=="bin" || dir[-1]=="sbin")
158 return dir/".."/"lib"/appname;
163 void chdir(const Path &path)
165 if(::chdir(path.str().c_str())==-1)
166 throw system_error("chdir");