[英]C++ _findfirst and TCHAR
我得到了以下代碼:
int _tmain(int argc, _TCHAR* argv[]) {
_finddata_t dirEntry;
intptr_t dirHandle;
dirHandle = _findfirst("C:/*", &dirEntry);
int res = (int)dirHandle;
while(res != -1) {
cout << dirEntry.name << endl;
res = _findnext(dirHandle, &dirEntry);
}
_findclose(dirHandle);
cin.get();
return (0);
}
這樣做是打印給定目錄(C :)包含的所有內容的名稱。 現在我必須打印出子目錄中所有內容的名稱(如果有的話)。 到目前為止我有這個:
int _tmain(int argc, _TCHAR* argv[]) {
_finddata_t dirEntry;
intptr_t dirHandle;
dirHandle = _findfirst(argv[1], &dirEntry);
vector<string> dirArray;
int res = (int)dirHandle;
unsigned int attribT;
while (res != -1) {
cout << dirEntry.name << endl;
res = _findnext(dirHandle, &dirEntry);
attribT = (dirEntry.attrib >> 4) & 1; //put the fifth bit into a temporary variable
//the fifth bit of attrib says if the current object that the _finddata instance contains is a folder.
if (attribT) { //if it is indeed a folder, continue (has been tested and confirmed already)
dirArray.push_back(dirEntry.name);
cout << "Pass" << endl;
//res = _findfirst(dirEntry.name, &dirEntry); //needs to get a variable which is the dirEntry.name combined with the directory specified in argv[1].
}
}
_findclose(dirHandle);
std::cin.get();
return (0);
}
現在我不是要求整個解決方案(我希望能夠自己完成)但是有一件事我無法理解這是TCHAR * argv。 我知道argv [1]包含我在“命令參數”下的項目屬性中放置的內容,現在它包含我想要在(C:/ users / name / New folder / *)中測試我的應用程序的目錄,其中包含一些包含子文件夾和一些隨機文件的文件夾。 argv [1]目前給出以下錯誤:
錯誤:類型“_TCHAR *”的參數與“const char *”類型的參數不兼容
現在我用Google搜索了TCHAR,我知道它是wchar_t *或char *取決於使用Unicode字符集或多字節字符集(我目前正在使用Unicode)。 我也明白轉換是一個巨大的痛苦。 所以我要問的是:我怎樣才能最好地利用_TCHAR和_findfirst參數解決這個問題?
我打算將dirEntry.name連接到argv [1],並在最后連接一個“*”,並在另一個_findfirst中使用它。 我對代碼的任何評論都很受歡迎,因為我還在學習C ++。
請參見此處: _findfirst用於多字節字符串,而_wfindfirst
用於寬字符。 如果在代碼中使用TCHAR,則使用_tfindfirst
(宏)將解析為非UNICODE上的_findfirst,以及UNICODE構建時的_wfindfirst。
而不是_finddata_t使用_tfinddata_t,它也將根據UNICODE配置解析為正確的結構。
另一件事是你應該使用正確的文字, _T("C:/*")
在UNICODE構建時將是L"C:/*"
,否則將是"C:/*"
。 如果您知道使用UNICODE定義構建,則使用std::vector<std::wstring>
。
順便說一句。 默認情況下,Visual Studio將使用UNICODE創建項目,您可能只使用_wfindfirst
等廣泛版本的函數,因為沒有充分的理由來構建非UNICODE項目。
TCHAR和我理解它是wchar_t *或char *取決於使用UTF-8字符集或多字節字符集(我目前使用的是UTF-8)。
這是錯誤的,在UNICODE窗口中,apis使用UTF-16。 sizeof(wchar_t)==2
。
使用這個簡單的typedef
:
typedef std::basic_string<TCHAR> TCharString;
然后在使用std::string
地方使用TCharString
,例如:
vector<TCharString> dirArray;
有關std :: basic_string的信息,請參見此處。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.