2 This file is part of libmsppath
3 Copyright © 2006 Mikko Rasa, Mikkosoft Productions
4 Distributed under the LGPL
12 #include <msp/strutils.h>
22 Fixes the case of the given path to match files / directories on the
23 filesystem. Intended to be used in programs that need to interact with
24 emulated Windows programs.
26 Path fix_case(const Path &path)
30 for(Path::iterator i=path.begin(); i!=path.end(); ++i)
38 files=list_files(result);
40 files=list_files(".");
43 for(list<string>::iterator j=files.begin(); (j!=files.end() && !found); ++j)
44 if(!strcasecmp(*j,*i))
59 Creates the given directory and any parent directories if needed.
61 @param path The path to create
62 @param mode Access mode for new directories
64 @return 0 on success, -1 on error
66 int mkpath(const Path &path, int mode)
69 for(Path::iterator i=path.begin(); i!=path.end(); ++i)
73 if(p.size()==1 && is_windows_drive(*i)) continue;
76 int err=stat(p.str().c_str(),&st);
79 if(!S_ISDIR(st.st_mode))
86 else if(errno!=ENOENT)
91 // The win32 version of this function doesn't take the mode argument. Go figure.
92 err=mkdir(p.str().c_str());
94 err=mkdir(p.str().c_str(),mode);
96 if(err==-1) return -1;
103 int rmdir(const Path &path, bool recursive)
107 list<string> files=list_files(path);
108 for(list<string>::iterator i=files.begin(); i!=files.end(); ++i)
112 stat(p.str().c_str(),&st);
114 if(S_ISDIR(st.st_mode))
117 err=unlink(p.str().c_str());
121 return rmdir(path.str().c_str());
125 Lists all files in a directory except the implied . and .. entries.
127 list<string> list_files(const Path &path)
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))) continue;
137 result.push_back(fn);
144 bool exists(const Path &path)
147 return !stat(path.str().c_str(),&st);
150 Filename splitext(const string &fn)
153 unsigned dot=fn.rfind('.');
154 result.base=fn.substr(0,dot);
155 if(dot!=string::npos)
156 result.ext=fn.substr(dot);
160 int fnmatch(const string &pat, const Path &fn)
165 return ::fnmatch(pat.c_str(), fn.str().c_str(), FNM_PATHNAME);
169 Path relative(const Path &path, const Path &base)
171 Path::iterator i=path.begin();
172 Path::iterator j=base.begin();
173 for(; (i!=path.end() && j!=base.end() && *i==*j); ++i,++j);
176 for(; j!=base.end(); ++j)
178 for(; i!=path.end(); ++i)
185 Extracts the basename from the given path. Same thing as Path::Path(p)[-1],
188 string basename(const std::string &p)
190 unsigned slash=p.rfind(DIRCHAR);
191 if(slash==string::npos)
194 return p.substr(slash+1);