Dr Deo
Dr Deo

Reputation: 4848

why is this function failing?

I am trying to understand windows hooks by writing a few keyboard hooks. I have a function:

bool WriteToFile(WPARAM keyCode, char * fileName)
{
    ofstream fout("filename");
    if(fout.is_open())
    {
        if(keyCode>=0x030 && keyCode<0x039)
            fout<< (keyCode - 0x030);
            fout.close();
        return true;
    }
    else        fout.close();
        return false;
}

...that i try to call from here but it almost always fails. Why?

LRESULT CALLBACK KbHookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
if(nCode > 0)
             {
                 WriteToFile(wParam,"log.txt");  //this function always fails . Why 
             }
else return CallNextHookEx(hCurrentHook, nCode, wParam, lParam);
}

Upvotes: 1

Views: 96

Answers (1)

dreamlax
dreamlax

Reputation: 95355

I think it's because you're trying to open a file called “filename”, rather than using whatever filename was provided. I assume you're writing a keylogger. It should read:

bool WriteToFile(WPARAM keyCode, char * fileName)
{
    // cause output to go to the end of the file by using ios_base::app
    ofstream fout(fileName, ios_base::app);
    if(fout.is_open())
    {
        if(keyCode>=0x030 && keyCode<0x039)
            fout<< (keyCode - 0x030);
            fout.close();
        return true;
    }
    else        fout.close();
        return false;
}

Upvotes: 4

Related Questions