0

I have wrote the following code:

int fd = _dup(fileno(stdout));
FILE* tmp = freopen("tmp","w+",stdout);
HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
if (out == INVALID_HANDLE_VALUE){
      //error
}
else if (out == NULL) {
      //error
}
else {
   WriteFile(out, "num", sizeof("num"), NULL, NULL);
 }

In the last line I get an assertion "Unhandled exception...:Access violation writing location 0x000000" What could be a problem and the fix for it?

Thank you.

P.S:Due to limitation of the project I can`t use freopen

YAKOVM
  • 9,805
  • 31
  • 116
  • 217
  • 1
    But you are using `freopen`? You check if it's an invalid handle or null and then proceed to write to the file anyway. In this case it appears that it was null. You may want a final `else` case before `WriteFile`. FYI I'd recommend `std::fstream` in C++ – AJG85 Apr 23 '12 at 19:38
  • @AJG85 - //Error command returns error descriptor,so it can`t get to WriteFile.BUT (for your conveneince) I have change the code for you.And error still occurs – YAKOVM Apr 23 '12 at 19:41

1 Answers1

4

Only one of the last two parameters to WriteFile can be NULL, the other must be a valid pointer.

http://msdn.microsoft.com/en-us/library/windows/desktop/aa365747.aspx

In your case you probably want to use lpNumberOfBytesWritten.

DWORD written;
WriteFile(out, "num", sizeof("num"), &written, NULL);
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622