[英]Printing a path to a file from a variable in C++
假設我有這個功能:
void printPathToFile( std::wstring myPath ){
std::wstringstream ss;
ss << myPath;
//When printing myPath as soon as there is a \ it stops so this information is lost.
ss << getOtherReleventLogingInformation();
std::wofstream myfile;
myfile.open ("C:\\log.txt", std::wofstream::app|std::wofstream::out);
myfile << ss.str();
myfile.close();
}
我不控制myPath
參數。 現在它的路徑名中沒有\\\\
,因此流將它們解釋為轉義序列,這不是我想要的。
如何使用 std::wstring 變量作為原始字符串?
如果它是一個字符串文字,我可以使用R"C:\\myPath\\"
但是我如何在沒有字符串文字的情況下實現同樣的目標?
一種可能的方法是遍歷路徑名並在需要的地方添加一個額外的反斜杠,但 C++ 肯定有更健壯和優雅的東西..?
編輯:
我的問題被誤診了。 結果反斜杠不會引起任何麻煩,我必須添加的是:
#include <codecvt>
#include <locale>
const std::locale utf8_locale
= std::locale(std::locale(), new std::codecvt_utf8<wchar_t>());
myFile.imbue(utf8_locale);
如此處所述: Windows Unicode C++ Stream Output Failure
文件路徑現在正確顯示,我認為使用wofstream
為您處理本地文件,因此非 ANSII 字符將正確顯示。
我建議您只需將\\\\
替換為/
,它們的工作方式相同(甚至更好,因為它們在所有平台上都有效):
void printPathToFile( std::wstring myPath )
{
std::wstring mySafePath = myPath;
std::replace( mySafePath.begin(), mySafePath.end(), '\\', '/');
// then use mySafePath in the rest of the function....
}
它確實:提升文件系統。 您使用path
來傳遞路徑,而不是字符串。 這是boost文件系統的hello world:
int main(int argc, char* argv[])
{
path p (argv[1]); // p reads clearer than argv[1] in the following code
if (exists(p)) // does p actually exist?
{
if (is_regular_file(p)) // is p a regular file?
cout << p << " size is " << file_size(p) << '\n';
else if (is_directory(p)) // is p a directory?
cout << p << "is a directory\n";
else
cout << p << "exists, but is neither a regular file nor a directory\n";
}
else
cout << p << "does not exist\n";
return 0;
}
http://www.boost.org/doc/libs/1_58_0/libs/filesystem/doc/tutorial.html
編輯:另請注意,該庫正在考慮添加到標准中,目前可以從 std::experimental 命名空間使用,具體取決於您的編譯器/標准庫版本:http ://en.cppreference.com/w/ cpp/頭文件/實驗/文件系統
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.