13

Is there any where to convert a open FILE* returned from fopen to a HANDLE that is used in the Windows API functions? If so, how?

小太郎
  • 5,510
  • 6
  • 37
  • 48
  • If you're willing to go the other way (which is more common), see this question http://stackoverflow.com/questions/5193579/how-make-file-from-handle-in-winapi which is creating a FILE * from a HANDLE. – Tony Lee May 19 '11 at 21:03

1 Answers1

14

(HANDLE)_get_osfhandle(_fileno( file ) )

Good luck on 64-bit systems if you're using Visual C++ 2008 or earlier, though, because the return type is long on those. :(

user541686
  • 205,094
  • 128
  • 528
  • 886
  • @Neil: Thanks. :) Why? Portability? – user541686 May 19 '11 at 20:59
  • 1
    @ Mehrdad The FILE * stuff is an abstraction, If you don't want an abstraction, don't use it. But you can't have a bit of an abstraction. –  May 19 '11 at 21:04
  • @Neil: Well the issue is, you sometimes need the C-style abstraction for reading/writing files, but you sometimes need more info about the file, which you can only get with [`GetFileInformationByHandle`](http://msdn.microsoft.com/en-us/library/aa364952(v=vs.85).aspx). It's not an ideal solution but it's easier and somewhat better than migrating your entire code to `ReadFile`/`WriteFile` usage -- at least in that way, it'll be easier to port your code to other platforms later. (Not sure why you say *can't*, though.) – user541686 May 19 '11 at 21:07
  • How does that snippet of code work though? Doesn't `_get_osfhandle` convert a HANDLE to a file descriptor? At least that's what's documented in the MSDN – 小太郎 May 19 '11 at 21:13
  • @小太郎: No, it's the other way around; check MSDN again. (It's called `_get_osfhandle` because it "Gets the Operating System File **Handle**".) – user541686 May 19 '11 at 21:14
  • Oh, I confused it with `_open_osfhandle` :P – 小太郎 May 19 '11 at 21:16
  • @Mehrdad So basically, hacks are OK? Fair enough, and I've certainly done my share of them. But I would still question the hack, even if it was mine. –  May 19 '11 at 21:22
  • @Neil: Haha well, depends. If there's no alternative then you can't do anything about it, right? :) – user541686 May 19 '11 at 21:25
  • One more question: Do I still need to close the handle returned by `_get_osfhandle` if I already `fclose`'d the original `FILE*`? – 小太郎 May 19 '11 at 21:25
  • @小太郎: Nope, you don't, because by definition `_get_osfhandle` is the *internal* handle for the `FILE`, which isn't supposed to be managed by you. – user541686 May 19 '11 at 21:27