【问题标题】:Count digits in file using WinApi functions使用 WinApi 函数计算文件中的数字
【发布时间】:2015-06-18 09:57:20
【问题描述】:

我需要使用来自<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,最好在读取文件时计算数字。

你能帮我解决这个问题吗?

更新

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

【问题讨论】:

    标签: c++ winapi createfile


    【解决方案1】:

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

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

    【讨论】:

    • 当我尝试运行该程序时,由于某种原因我收到错误消息。请看更新,有截图
    • 我认为你需要使用iswdigit()的宽字符版
    【解决方案2】:

    阅读https://msdn.microsoft.com/en-us/library/wt3s3k55.aspx的以下说明

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-02
      • 1970-01-01
      相关资源
      最近更新 更多