私は持っています
const char *pathname = "..\somepath\somemorepath\somefile.ext";
それをに変換する方法
"..\somepath\somemorepath"
?
私は持っています
const char *pathname = "..\somepath\somemorepath\somefile.ext";
それをに変換する方法
"..\somepath\somemorepath"
?
最も簡単な方法は、find_last_of
のメンバー関数を使用することですstd::string
string s1("../somepath/somemorepath/somefile.ext");
string s2("..\\somepath\\somemorepath\\somefile.ext");
cout << s1.substr(0, s1.find_last_of("\\/")) << endl;
cout << s2.substr(0, s2.find_last_of("\\/")) << endl;
このソリューションは、スラッシュとバックスラッシュの両方で機能します。
Windowsの使用_splitpath()
とLinuxの使用dirname()
Windows 8では、次の場所で使用PathCchRemoveFileSpec
できます。Pathcch.h
PathCchRemoveFileSpec
パスの最後の要素が削除されるため、ディレクトリパスを渡すと、最後のフォルダが削除されます。
これを避けたい場合で、ファイルパスがディレクトリかどうかわからない場合は、次を使用してください。PathIsDirectory
PathCchRemoveFileSpec
スラッシュを含むパスでは期待どおりに動作しません。
strrchr()
最後のバックスラッシュを見つけて文字列を削除するために使用します。
char *pos = strrchr(pathname, '\\');
if (pos != NULL) {
*pos = '\0'; //this will put the null terminator here. you can also copy to another string if you want
}
PathRemoveFileSpec(...)これにはWindows8は必要ありません。Shlwapi.hとShlwapi.libを含める必要がありますが、これらはwinapiであるため、特別なSDKは必要ありません。