2

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
  • 64,417
  • 29
  • 168
  • 201

1 Answers1

9

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
  • 794
  • 1
  • 4
  • 8