29

私は持っています

const char *pathname = "..\somepath\somemorepath\somefile.ext";

それをに変換する方法

"..\somepath\somemorepath"

4

5 に答える 5

59

最も簡単な方法は、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;

このソリューションは、スラッシュとバックスラッシュの両方で機能します。

于 2012-04-28T15:29:28.080 に答える
9

Windowsの使用_splitpath()とLinuxの使用dirname()

于 2012-04-28T15:26:44.447 に答える
6

Windows 8では、次の場所で使用PathCchRemoveFileSpecできます。Pathcch.h

PathCchRemoveFileSpecパスの最後の要素が削除されるため、ディレクトリパスを渡すと、最後のフォルダが削除されます。
これを避けたい場合で、ファイルパスがディレクトリかどうかわからない場合は、次を使用してください。PathIsDirectory

PathCchRemoveFileSpecスラッシュを含むパスでは期待どおりに動作しません。

于 2013-09-11T00:34:12.757 に答える
3

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
}
于 2012-04-28T15:26:34.133 に答える
0

PathRemoveFileSpec(...)これにはWindows8は必要ありません。Shlwapi.hとShlwapi.libを含める必要がありますが、これらはwinapiであるため、特別なSDKは必要ありません。

于 2019-10-10T22:43:11.480 に答える