我正在尝试创建一个重命名目录结构中文件的函数。我面临的问题是,在Microsoft Visual Studio 2013快速版中设置unicode字符集时,我编写的以下代码无法编译。
我知道unicode有相同的功能,但我无法使代码工作。关于如何使这个工作为unicode的任何输入都是最受欢迎的。
以下是代码:
void Subdir(char st[1000]){
char *s;
char sDir[MAX_PATH] = "\0", sTmp[MAX_PATH] = "\0";
int gasit;
WIN32_FIND_DATA theFiles;
HANDLE hTheFiles;
ZeroMemory(&theFiles, sizeof(WIN32_FIND_DATA));
s = st;
strcat(s, "\\");
strcpy_s(sDir, s);
strcat_s(sDir, "*");
rezultat.resize(0);
hTheFiles = FindFirstFile(sDir, &theFiles);
if (hTheFiles == INVALID_HANDLE_VALUE) return;
sDir[strlen(sDir) - 1] = 0;
do {
if ((!strcmp(".", theFiles.cFileName)) || (!strcmp("..", theFiles.cFileName)))
continue;
if (theFiles.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY){
strcpy_s(sTmp, sDir);
strcat_s(sTmp, theFiles.cFileName);
strcat_s(sTmp, "\\");
FisiereSubdir(sTmp);
}
else {
std::string str(s);
gasit = str.find_first_of("\\");
while (gasit != string::npos){
if (gasit > 0){
rezultat.push_back(str.substr(0, gasit));
}
str = str.substr(gasit + 1);
gasit = str.find_first_of("\\");
}
if (str.length() > 0){
rezultat.push_back(s);
}
k = rezultat.size();
//(cin.get() << '\n');
if ((k % 4) == 0)
{
f_path = rezultat[k - 2] + string("_") + rezultat[k - 1] + string("_") + theFiles.cFileName;
const char * nume_nou = f_path.c_str();
const char * nume_vechi = theFiles.cFileName;
if (_chdir(s))
{
switch (errno)
{
case ENOENT:
printf("No such directory: %s\n");
break;
case EINVAL:
printf("Incorect parameter.\n");
break;
default:
printf("Unknown error.\n");
}
}
else
{
redenumit = rename(nume_vechi, nume_nou);
if (redenumit == 0)
puts("Modification done !");
else
perror("Modification impossible !");
}
}
}
} while (FindNextFile(hTheFiles, &theFiles));
FindClose(hTheFiles);
return;
}
答案 0 :(得分:0)
在Win32中,大多数API函数实际上都是基于您是否使用unicode的条件定义,如下所示(当光标位于标识符上时,点击F12以查看定义,或右键单击 - &gt;转到visual studio中的定义:
#ifdef UNICODE
#define SomeWin32Function SomeWin32FunctionW
#else
#define SomeWin32Function SomeWin32FunctionA
#endif
基本上,Win32函数的unicode版本需要wchar_t*
和wchar_t
个字符。 ANSI需要char*
和char
个字符。当然,Unicode的区别在于16位字符集,ANSI是8位字符集,不同字符集的处理方式也不同。
考虑到这一点,我注意到一些事情应该解决这个问题:
char *
和char
替换为wchar_t *
和wchar_t
(或WCHAR
typedef)。std::string
替换为std::wstring
"\\"
使用宽字符等效L"\\"
#define UNICODE
自动调用ANSI或unicode版本。诸如strcat
之类的函数需要用适当的函数替换,例如wcscat
(宽字符串连接)。这是至少strcat宽字符版本的msdn参考页面,其他字符串函数(如strcmp
,strcpy
等)具有类似的命名约定:http://msdn.microsoft.com/en-us/library/h1x0y282.aspx