1

See title.

How do I achieve the opposite of this question: How do I get the file HANDLE from the fopen FILE structure?

I create the handle with

      HANDLE h = CreateFile(name,
                            GENERIC_WRITE,
                            0,
                            NULL,
                            OPEN_ALWAYS,
                            FILE_ATTRIBUTE_NORMAL,
                            NULL);

and then try to write some data to it using fputs.

The call to fputs fails on the line

_VALIDATE_STREAM_ANSI_RETURN(stream, EINVAL, EOF);

where stream is the handle I obtained from CreateFile.


The reason why I'm doing that is that I use an external library that uses FILE* handles and I'm not opening a plain file (as until now) but trying to write to a pipe instead. And changing the external library is not an option.

Community
  • 1
  • 1
eckes
  • 56,506
  • 25
  • 151
  • 189

2 Answers2

8

Don't know if this is the best way but see _open_osfhandle():

http://msdn.microsoft.com/en-us/library/bdts1c9x(v=vs.71).aspx

int fd = _open_osfhandle(h, ...);

It returns a file descriptor which you'll have to open using fdopen to get a FILE*.

FILE* fp = _fdopen(fd, ...);
Emil Romanus
  • 754
  • 1
  • 4
  • 8
1

CreateFile returns internal Windows handle to the file. You can write to the file using this handle using functions like WriteFile.

To use fputs, you need to open the file with fopen function in C. If you do that, you won't need to call CreateFile explicitly, as fopen will do it for you if called with parameter "w" (for 'write').

As such, I don't think what you're after is possible. The two sets of functions are not compatible.

Aleks G
  • 52,841
  • 25
  • 149
  • 233
  • 1
    (and upvoters): see the answer of Emil. It works for me. Is there anything wrong with that approach (if so, please comment to his answer)? – eckes Sep 09 '11 at 09:04
  • Thanks for the pointer (no pun intended). That's a great find. – Aleks G Sep 09 '11 at 09:18