-1

The documentation for OpenFile function in Windows is located here. And I am trying to do this:

#include "Tchar.h"
#include <windows.h>
int main(int argc, TCHAR *argv[]){

    LPOFSTRUCT _buffer;
    HFILE _hfile_ = OpenFile("E:\\mozunit.txt", _buffer, OF_READ);
    LPVOID _buffer_read;
    LPDWORD _bytes_read;
    bool flag = ReadFile(_buffer, _buffer_read, 5, _bytes_read, NULL);
    CloseHandle(_buffer);
    return 0;
}

Now, when I run this I get an error that I have not initialized the _buffer. So to counter that I initialized _buffer like this:

LPOFSTRUCT _buffer = NULL;

Which gives me an access violation error. Why is that?

user1343318
  • 2,093
  • 6
  • 32
  • 59
  • 2
    So I read your reference page, and it says nowhere that `NULL` is a valid value for the requested buffer. – Jongware Nov 11 '13 at 20:29
  • A couple of the answers correctly point out the problem. In addition, note that OpenFile has been deprecated for a long time. You should be using CreateFile. Despite its name, CreateFile can open an existing file. – Adrian McCarthy Nov 11 '13 at 21:40

2 Answers2

6

According to the documentation, the second argument is...

A pointer to the OFSTRUCT structure that receives information about a file when it is first opened.

By setting it to NULL you're attempting to write to memory with the address of zero.

Try this instead:

OFSTRUCT buffer;
HFILE hfile = OpenFile("E:\\mozunit.txt", &buffer, OF_READ);
char buffer_read[6];
DWORD bytes_read = 0;
bool flag = ReadFile(hfile, &buffer_read, 5, &bytes_read, NULL);
CloseHandle(hfile);
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
3

You need to pass a pointer to an allocated LPOFSTRUCT object to OpenFile. You are passing NULL to a function that expects a valid memory, not NULL. You declare an OFSTRUCT object and pass a pointer to it to OpenFile

You have the same issue for the parameters that you pass in ReadFile. And you need to call CloseFile on the _hFile_ file handle, not on the _buffer. The same goes for ReadFile Finally you shouldn't be using OpenFile anyway - you should be using CreateFile as the documentation states.

Your code should be something more like:

#include "Tchar.h"
#include <windows.h>
int main(int argc, TCHAR *argv[]){

    OFSTRUCT _buffer = {0};  // Create an OFSTRUCT structure local variable and initialize it to zero.
    HFILE _hfile_ = OpenFile("E:\\mozunit.txt", &_buffer, OF_READ);
    char _buffer_read[5];
    DWORD _bytes_read;
    bool flag = ReadFile(_hfile_ , _buffer_read, 5, &_bytes_read, NULL);
    CloseHandle(_hfile_ );
    return 0;
}
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
shf301
  • 31,086
  • 2
  • 52
  • 86