10 #include <msp/core/systemerror.h>
11 #include <msp/strings/regex.h>
12 #include <msp/strings/utils.h>
26 /** Helper function to determine the location of the program's executable.
27 Caches the last result to cut down filesystem access with repeated calls. */
28 const Path &get_bin_dir(const string &argv0)
30 static string last_argv0;
33 if(!(argv0==last_argv0))
36 if(argv0.find('/')==string::npos)
38 const char *path = getenv("PATH");
39 vector<string> dirs = split(path, ':');
40 for(vector<string>::const_iterator i=dirs.begin(); i!=dirs.end(); ++i)
41 if(exists(Path(*i)/argv0))
43 exe = realpath(Path(*i)/argv0);
48 exe = realpath(argv0);
51 bin_dir = dirname(exe);
60 not_a_directory::not_a_directory(const Path &p):
61 runtime_error(p.str())
65 void mkdir(const Path &path, int mode)
69 // The win32 version of this function doesn't take the mode argument. Go figure.
71 err = ::mkdir(path.str().c_str());
73 err = ::mkdir(path.str().c_str(), mode);
77 throw system_error("mkdir");
80 void mkpath(const Path &path, int mode)
83 for(Path::Iterator i=path.begin(); i!=path.end(); ++i)
87 if(p.size()==1 && p.is_absolute())
93 throw not_a_directory(p);
101 void rmdir(const Path &path)
103 if(::rmdir(path.str().c_str())==-1)
104 throw system_error("rmdir");
107 void rmpath(const Path &path)
109 list<string> files = list_files(path);
110 for(list<string>::iterator i=files.begin(); i!=files.end(); ++i)
122 list<string> list_files(const Path &path)
124 return list_filtered(path, string());
127 list<string> list_filtered(const Path &path, const string &filter)
129 Regex r_filter(filter);
132 DIR *dir = opendir(path.str().c_str());
135 while(dirent *de = readdir(dir))
137 const char *fn = de->d_name;
138 if(fn[0]=='.' && (fn[1]==0 || (fn[1]=='.' && fn[2]==0)))
140 if(r_filter.match(fn))
141 result.push_back(fn);
152 return ::getcwd(buf, sizeof(buf));
159 if(SHGetFolderPath(0, CSIDL_PERSONAL, 0, 0, home)==S_OK)
162 const char *home = getenv("HOME");
169 Path get_user_data_dir(const string &appname)
172 char datadir[MAX_PATH];
173 if(SHGetFolderPath(0, CSIDL_LOCAL_APPDATA, 0, 0, datadir)==S_OK)
174 return Path(datadir)/appname;
177 return get_home_dir()/("."+appname);
181 Path get_sys_conf_dir(const string &argv0)
183 Path dir = get_bin_dir(argv0);
185 if(dir[-1]=="bin" || dir[-1]=="sbin")
196 Path get_sys_data_dir(const string &argv0, const string &appname)
198 Path dir = get_bin_dir(argv0);
200 if(dir[-1]=="bin" || dir[-1]=="sbin")
201 return dir/".."/"share"/appname;
206 Path get_sys_lib_dir(const string &argv0, const string &appname)
208 Path dir = get_bin_dir(argv0);
210 if(dir[-1]=="bin" || dir[-1]=="sbin")
211 return dir/".."/"lib"/appname;
216 void chdir(const Path &path)
218 if(::chdir(path.str().c_str())==-1)
219 throw system_error("chdir");