8 #include <msp/core/systemerror.h>
9 #include <msp/strings/regex.h>
10 #include <msp/strings/utils.h>
24 /** Helper function to determine the location of the program's executable.
25 Caches the last result to cut down filesystem access with repeated calls. */
26 const Path &get_bin_dir(const string &argv0)
28 static string last_argv0;
31 if(!(argv0==last_argv0))
34 if(argv0.find('/')==string::npos)
36 const char *path = getenv("PATH");
37 vector<string> dirs = split(path, ':');
38 for(vector<string>::const_iterator i=dirs.begin(); i!=dirs.end(); ++i)
39 if(exists(Path(*i)/argv0))
41 exe = realpath(Path(*i)/argv0);
46 exe = realpath(argv0);
49 bin_dir = dirname(exe);
58 not_a_directory::not_a_directory(const Path &p):
59 runtime_error(p.str())
63 void mkdir(const Path &path, int mode)
67 // The win32 version of this function doesn't take the mode argument. Go figure.
69 err = ::mkdir(path.str().c_str());
71 err = ::mkdir(path.str().c_str(), mode);
75 throw system_error("mkdir");
78 void mkpath(const Path &path, int mode)
81 for(Path::Iterator i=path.begin(); i!=path.end(); ++i)
85 if(p.size()==1 && p.is_absolute())
91 throw not_a_directory(p);
99 void rmdir(const Path &path)
101 if(::rmdir(path.str().c_str())==-1)
102 throw system_error("rmdir");
105 void rmdirs(const Path &path)
107 list<string> files = list_files(path);
108 for(list<string>::iterator i=files.begin(); i!=files.end(); ++i)
120 list<string> list_files(const Path &path)
122 return list_filtered(path, string());
125 list<string> list_filtered(const Path &path, const string &filter)
127 Regex r_filter(filter);
130 DIR *dir = opendir(path.str().c_str());
133 while(dirent *de = readdir(dir))
135 const char *fn = de->d_name;
136 if(fn[0]=='.' && (fn[1]==0 || (fn[1]=='.' && fn[2]==0)))
138 if(r_filter.match(fn))
139 result.push_back(fn);
150 return ::getcwd(buf, sizeof(buf));
157 if(SHGetFolderPath(0, CSIDL_PERSONAL, 0, 0, home)==S_OK)
160 const char *home = getenv("HOME");
167 Path get_user_data_dir(const string &appname)
170 char datadir[MAX_PATH];
171 if(SHGetFolderPath(0, CSIDL_LOCAL_APPDATA, 0, 0, datadir)==S_OK)
172 return Path(datadir)/appname;
175 return get_home_dir()/("."+appname);
179 Path get_sys_conf_dir(const string &argv0)
181 Path dir = get_bin_dir(argv0);
183 if(dir[-1]=="bin" || dir[-1]=="sbin")
194 Path get_sys_data_dir(const string &argv0, const string &appname)
196 Path dir = get_bin_dir(argv0);
198 if(dir[-1]=="bin" || dir[-1]=="sbin")
199 return dir/".."/"share"/appname;
204 Path get_sys_lib_dir(const string &argv0, const string &appname)
206 Path dir = get_bin_dir(argv0);
208 if(dir[-1]=="bin" || dir[-1]=="sbin")
209 return dir/".."/"lib"/appname;
214 void chdir(const Path &path)
216 if(::chdir(path.str().c_str())==-1)
217 throw system_error("chdir");