使用 WinApi 函数计算文件中的数字

Count digits in file using WinApi functions

我需要使用 <Windows.h> 中的 CreateFileReadFile 方法计算文件中的数字。

这是我拥有的:

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 并且最好在从文件中读取时计算数字。

你能帮我解决一下吗?

更新

这是我在 运行 程序时得到的:

您不需要创建 std::string 的额外复杂程度,您已经以字符数组的形式获得了它,您可以使用 dwRead,这是没有。 ReadFile() 读取的字节数。

for (int i = 0; i < dwRead; ++i)
    if (iswdigit(data[i]))
        count++;

阅读来自 https://msdn.microsoft.com/en-us/library/wt3s3k55.aspx

的以下注释

wchar_t 的大小是实现定义的。如果您的代码依赖 wchar_t 为特定大小,请检查您平台的实现(例如,使用 sizeof(wchar_t))。如果您需要保证在所有平台上保持相同宽度的字符串字符类型,请使用 string、u16string 或 u32string。

如果您确定您的文件不包含任何 unicode 或多字节字符,那么最好按 char 来解析 char