tags:

views:

26

answers:

2

Hi, I know what is my mistake can't figer how to solve it.

Im writing an winAPI that counts how many 'a' characters are found is a givien file. Im still getting the error " subscript requires array or pointer " (please find the comment in the code)

#include "stdafx.h"
#include <windows.h>


int _tmain(int argc, _TCHAR* argv[])
{
    WCHAR str=L'a';
    HANDLE A;
    TCHAR *fn;

    fn=L"d:\\test.txt";
    A= CreateFile(fn,GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);

    if(A==INVALID_HANDLE_VALUE)
    {
        _tprintf(L"cannot open file \n");
    }

    else
    {
        DWORD really;
        int countletter;
        int stringsize;
        do
        {
            BYTE x[1024];


            ReadFile(A,x,1024,&really,NULL);
            stringsize = sizeof(really);
            for(int i =0;i<stringsize;i++)
            {

                if(really[i]==str)   //here Im getting the error
                    countletter++;
            }
        }while(really==1024);

            CloseHandle(A);
            _tprintf(L"NUmbers of A's found is %d \n",countletter);
    }

    return 0;
}

now I know I can't make comparesion between array and a WCHAR but hw to fix it ?

A: 

ReadFile() puts the data into the second parameter, in your case x.

In your code, really is the number of bytes read. It's just a number. You can't put an subscript on a plain number, thus the error message.

So change

if(really[i]==str)

To

if (x[i] == str) 

But you're going to hit another problem:

DWORD really;
int countletter;
int stringsize;

do {
    BYTE x[1024];

    bool bResult = ReadFile(A, x, 1024, &really, NULL); // must save the result
    if (bResult) 
        break; // Error!

    // stringsize = sizeof(really); // <== NO NO NO will always return 8
    stringsize = really;  // this is what you need

    for (int i = 0; i < stringsize; i++)
    {
        if(x[i] == str)
            countletter++;
    }
} while (really == 1024);

You'll need some error handling of course, and you really need meaningful variable names. Your problem would have been obvious if you had used inputBuffer and bytesRead instead of x and really.

Edited to add:

Your comment is correct, my previous edit went too far. It's true that the next-to-last read should return 1024 bytes, while the last will return < 1024. But I would still check for bytesRead == 0 right after the read, because it's easier to understand.

egrunin
I liked your way in explaining but Sir I kept using the do-while and I took x the input buffer to compaire and its showing right answers can you explain why if i keep using do-while will consider an issue , Again thanx for you help
Kristian
+1  A: 

Your variable really is neither an array nor a pointer, so subscripting it (really[i]) is illegal.

Dave Costa