使 WCHAR 为空终止

WBu*_*Bun 6 visual-c++

我有这个

WCHAR 文件名[1];

作为函数的返回值(它是 sys 32 函数,因此我无法更改返回的类型)。我需要使 fileName 以 null 结尾,因此我尝试将 '\0' 附加到它,但似乎没有任何效果。

一旦我得到一个以 null 结尾的 WCHAR,我将需要将其传递给另一个 sys 32 函数,因此我需要它保持为 WCHAR。

有人可以给我任何建议吗?

=================================================

非常感谢您的帮助。看来我的问题不仅仅与缺少空终止字符串有关。

//这有效:

WCHAR szPath1[50] = L"\\Invalid2.txt.txt";
    dwResult = FbwfCommitFile(szDrive, pPath1); //Successful
Run Code Online (Sandbox Code Playgroud)

//这不会:

std::wstring l_fn(L"\\");  
    //Because Cache_detail->fileName is \Invalid2.txt.txt and I need two
l_fn.append(Cache_detail->fileName);
l_fn += L""; //To ensure null terminated
fprintf(output, "l_fn.c_str: %ls\n", l_fn.c_str()); //Prints "\\Invalid2.txt.txt"

    iCommitErr = FbwfCommitFile(L"C:", (WCHAR*)l_fn.c_str()); //Unsuccessful
Run Code Online (Sandbox Code Playgroud)

//然后当我对这两者进行比较时,它们是不平等的。

int iCompareResult = l_fn.compare(pPath1);  // returns -1
Run Code Online (Sandbox Code Playgroud)

所以我需要弄清楚这两者最终是如何不同的。

多谢!

shf*_*301 7

由于您在评论中提到了 fbwffindfirst/fbwffindnext ,因此您正在谈论FbwfCacheDetail中返回的文件名。因此,从 fileNameLength 字段中您可以知道文件名的长度(以字节为单位)。WCHAR 中 fileName 的长度为 fileNameLength/sizeof(WCHAR)。所以简单的答案是你可以设置

fileName[fileNameLength/sizeof(WCHAR)+1] = L'\0'
Run Code Online (Sandbox Code Playgroud)

现在这一点很重要,您需要确保为 fbwffindfirst/fbwffindnext 发送的 cacheDetail 参数的缓冲区的 sizeof(WCHAR) 字节比您需要的大,上面的代码片段可能会在数组范围之外运行。因此,对于 fbwffindfirst/fbwffinnext 的大小参数,传入缓冲区大小 - sizeof(WCHAR)。

例如这个:

// *** Caution: This example has no error checking, nor has it been compiled ***
ULONG error;
ULONG size;
FbwfCacheDetail *cacheDetail;

// Make an intial call to find how big of a buffer we need
size = 0;
error = FbwfFindFirst(volume, NULL, &size);
if (error == ERROR_MORE_DATA) {
    // Allocate more than we need
    cacheDetail = (FbwfCacheDetail*)malloc(size + sizeof(WCHAR));
    // Don't tell this call about the bytes we allocated for the null
    error = FbwfFindFirstFile(volume, cacheDetail, &size);
    cacheDetail->fileName[cacheDetail->fileNameLength/sizeof(WCHAR)+1] = L"\0";

    // ... Use fileName as a null terminated string ...

    // Have to free what we allocate
    free(cacheDetail);
}
Run Code Online (Sandbox Code Playgroud)

当然,您必须进行一些更改才能适应您的代码(另外您还必须调用 fbwfffinndnext )

如果您对为什么 FbwfCacheDetail 结构以 WCHAR[1] 字段结尾感兴趣,请参阅此博客文章。这是 Windows API 中非常常见的模式。