0

I would like to use file stream functions (e.g., "ftell") on an existing file I opened using CreateFile (which returns a HANDLE). I searched SO and elsewhere with no joy. I want to do something like this:

HANDLE h;
FILE *f;
int pos;
h = CreateFile( "MYFILE.TXT", ... )
f = *convert*( h, &f );    // the function I'm looking for  
pos = ftell( f );

Is there a way to get a FILE stream from a file handle?

DontPanic
  • 2,164
  • 5
  • 29
  • 56
  • 1
    `_open_osfhandle()` to travel to the 1970s, `_fdopen()` to teleport back to the 1980s – Hans Passant Dec 26 '21 at 22:52
  • 1
    what sense in *ftell* ? – RbMm Dec 26 '21 at 23:07
  • *"I would like to use file stream functions (e.g., "ftell")"* - Why would any one willingly want to do that? Why step back into POSIX, the Stone Age of computing, where files had a hard limit of 2GB? – IInspectable Dec 27 '21 at 08:44
  • Responders: I am maintaining a 15-year old legacy app built with VC6.0 wherein I can find no modern, politically correct solutions. In any case, with all due respect, my question was "HOW" to do this, not "WHY" I shouldn't do this. BTW - The "HOW" is actually answered in the cited answer. – DontPanic Dec 27 '21 at 17:01
  • 1
    [`SetFilePointer`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-setfilepointer) had always been available, no matter how legacy you claim your code to be, or whether you would need Visual C++ 6 to compile it. – IInspectable Dec 28 '21 at 09:14
  • My Bad, I see now that I SHOULD use SetFilePointer even in VC6.0. – DontPanic Dec 29 '21 at 16:05

1 Answers1

1

Use _open_osfhandle() to create a C-style file descriptor from a Win32 HANDLE, and then use _fdopen() to create a FILE* from the file descriptor.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770