【发布时间】:2015-06-18 09:57:20
【问题描述】:
我需要使用来自<Windows.h> 的CreateFile 和ReadFile 方法计算文件中的数字。
这是我所拥有的:
int CountDigitsInFile(PCTSTR path)
{
HANDLE hFile = CreateFile(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
_tprintf_s(TEXT("Open File Error"));
return NULL;
}
TCHAR data[100];
DWORD dwRead;
DWORD dwFileSize = GetFileSize(hFile, NULL);
BOOL bResultRead = ReadFile(hFile, &data, dwFileSize, &dwRead, NULL);
if (!bResultRead || dwRead != dwFileSize)
{
_tprintf_s(TEXT("Read file Error"));
return NULL;
}
_tprintf_s(data); // prints the file content correctly
int count = 0;
wstring str(data);
std::cout << str.size() << std::endl; // prints 105 when file content is the following: Hello, World!5
for (int i = 0; i < str.size(); ++i) // fails somewhere here
if (isdigit(str[i]))
count++;
CloseHandle(hFile);
return count;
}
可能我以错误的方式计算它们,我必须逐字节计算或其他什么?而且我认为我真的不应该在这里使用wstring,最好在读取文件时计算数字。
你能帮我解决这个问题吗?
更新
这是我在运行程序时得到的结果:
【问题讨论】:
标签: c++ winapi createfile