[C/C++標準庫]_[初級]_[構造檔案路徑(stringByAppendingPathComponent)]

來源:互聯網
上載者:User

標籤:c++   檔案路徑   合并   串連   stringbyappendingpat   


情境:

1. 很多情況下需要通過檔案夾和檔案名稱拼接檔案路徑字串,每次都需要判斷是否需要添加路徑分隔字元seperator很麻煩,所以可以寫一個通用函數.

2. 大多數情況下都是windows使用wstring,mac使用string,所以用模版實現最通用.


函數:

template<class T>T AppendPathComponent(const T& source,const T& component){int length = source.length();int last = (length)?(length-1):0;if(source[last] == 0x5C || source[last] == 0x2F){return source+component;}else{T path(source);path.resize(length+1);path[length] = 0x2F;path.append(component);return path;}}inline char* Unicode2Ansi(const wchar_t* unicode)  {      int len;      len = WideCharToMultiByte(CP_ACP, 0, unicode, -1, NULL, 0, NULL, NULL);      char *szUtf8 = (char*)malloc(len + 1);      memset(szUtf8, 0, len + 1);      WideCharToMultiByte(CP_ACP, 0,unicode, -1, szUtf8, len, NULL,NULL);      return szUtf8;  } 

調用:

std::wstring wpath(L"C:\\info/中文");std::wstring wpath_1 = AppendPathComponent(wpath,std::wstring(L"info.txt"));cout << Unicode2Ansi(wpath_1.c_str()) << endl;std::string path("C:\\info");std::string path_1 = AppendPathComponent(path,std::string("info.txt"));cout << path_1.c_str()<< endl;

輸出:

C:\info/中文/info.txtC:\info/info.txt



[C/C++標準庫]_[初級]_[構造檔案路徑(stringByAppendingPathComponent)]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.