如何在C中读取文件并将其存储到WCHAR_T中?
我正在尝试从.txt
文件中获取 a.txt 的文件,并带有readfile()
函数,该函数由提供。 < windows.h>
,并将其存储在wchar_t []
变量中。这是我的代码:
#include <stdio.h>
#include <windows.h>
#include <io.h>
#include <fcntl.h>
int main() {
_setmode(_fileno(stdout), _O_U16TEXT);
_setmode(_fileno(stdin), _O_U16TEXT);
_setmode(_fileno(stderr), _O_U16TEXT);
HANDLE fh = CreateFileW(
L"a.txt",
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
LARGE_INTEGER size;
GetFileSizeEx(fh, &size);
DWORD sizeF = size.QuadPart;
wchar_t *readBuffer = (wchar_t *)malloc(sizeF * sizeof(wchar_t));
DWORD bytesRead;
if (ReadFile(fh, readBuffer, sizeF, &bytesRead, NULL)) {
readBuffer[sizeF] = L'\0';
}
wprintf(L"%s\n", readBuffer);
CloseHandle(fh);
}
但是我获得的输出不是我所期望的。它是正方形中的问号:
我的代码有什么问题?
I am trying to get info from a .txt
file called a.txt with the ReadFile()
function, which is provided by <windows.h>
, and store it in a wchar_t[]
variable. Here is my code:
#include <stdio.h>
#include <windows.h>
#include <io.h>
#include <fcntl.h>
int main() {
_setmode(_fileno(stdout), _O_U16TEXT);
_setmode(_fileno(stdin), _O_U16TEXT);
_setmode(_fileno(stderr), _O_U16TEXT);
HANDLE fh = CreateFileW(
L"a.txt",
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
LARGE_INTEGER size;
GetFileSizeEx(fh, &size);
DWORD sizeF = size.QuadPart;
wchar_t *readBuffer = (wchar_t *)malloc(sizeF * sizeof(wchar_t));
DWORD bytesRead;
if (ReadFile(fh, readBuffer, sizeF, &bytesRead, NULL)) {
readBuffer[sizeF] = L'\0';
}
wprintf(L"%s\n", readBuffer);
CloseHandle(fh);
}
But the output I get is not what I expected. It is question marks in squares:
What is wrong with my code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
分配大小存在一个明显的错误:您应该为
sizef + 1
元素分配空间,以便您可以在deadBuffer [sizef]
上设置一个null终结器。对分配错误的测试似乎更安全,尤其是因为分配大小可能非常大。
这里还有另一个问题:
wprintf(l“%s \ n”,readbuffer);
您应该使用%ls
输出wchar_t ,
%s
期望包含多键表示的char
的数组。还不清楚为什么您要调用
_SETMODE(_FILENO(STDOUT),_O_U16TEXT);
在所有3个标准流手柄上。我不确定您使用的专有API的精确语义...使用标准功能似乎更简单,更便携。
There is an obvious mistake in the allocation size: you should allocate space for
sizeF + 1
elements so you can set a null terminator atreadBuffer[sizeF]
.Testing for allocation error seems safer, especially since the allocation size may be very large.
There is another problem here:
wprintf(L"%s\n", readBuffer);
You should use%ls
to output an array ofwchar_t
,%s
expects an array ofchar
containing multibyte representations.It is also unclear why you call
_setmode(_fileno(stdout), _O_U16TEXT);
on all 3 standard stream handles.I am not sure about the precise semantics of the proprietary APIs you use... Using standard functions seems both simpler and more portable.