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:
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().