Count digits in file using WinApi functions

353 views Asked by At

I need to count digits in file using CreateFile and ReadFile methods from <Windows.h>.

Here's what I have:

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;   
}

Probably I'm counting them in a wrong way and I have to count byte by byte or something? And I think I really shouldn't use wstring here and it's better to count digits just while reading from the file.

Could you please help me with that?

UPDATE

Here's what I get when running the program: enter image description here

2

There are 2 answers

2
acraig5075 On BEST ANSWER

You don't need the extra level of complexity of creating a std::string, you've already got it in the form of a char array, and you can make use of dwRead, which is the no. of bytes read by ReadFile().

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

Read following note from https://msdn.microsoft.com/en-us/library/wt3s3k55.aspx

The size of wchar_t is implementation-defined. If your code depends on wchar_t to be a certain size, check your platform's implementation (for example, with sizeof(wchar_t)). If you need a string character type with a width that is guaranteed to remain the same on all platforms, use string, u16string, or u32string.

If you are sure that your file does not contain any unicode or multibyte characters then its better to parse char by char