Microsoft KB Archive/139640

= Do Not Mix Operating System and CRT File Handles =

Article ID: 139640

Article Last Modified on 12/1/2003

-

APPLIES TO


 * Microsoft Visual C++ 2.0 Professional Edition
 * Microsoft Visual C++ 2.1
 * Microsoft Visual C++ 2.2
 * Microsoft Visual C++ 4.0 Standard Edition
 * Microsoft Visual C++ 5.0 Enterprise Edition
 * Microsoft Visual C++ 6.0 Enterprise Edition
 * Microsoft Visual C++ 5.0 Professional Edition
 * Microsoft Visual C++ 6.0 Professional Edition
 * Microsoft Visual C++ 6.0 Standard Edition

-



This article was previously published under Q139640



SUMMARY
In 32-bit Windows-based applications, Windows API functions (OpenFile, CreateFile, and so on) return a file handle that cannot be substituted for a handle returned by a C Runtime Function (_open, _wopen, and so on). You can convert an operating system handle to a CRT handle by using the CRT function _open_osfhandle as demonstrated in the "Sample Code" section of this article.

NOTE: This distinction is not Win32 specific. However, some programmers using 16-bit products on 16-bit operating systems have mixed operating system and CRT file handles.



MORE INFORMATION
The following sample code shows how to open a file stream from a file handle returned by the OpenFile Windows API function.

Sample Code
/* Compile options needed:none
 * 1) include 
 * 2) include 
 * 3) include 
 * 4) include 
 * 5) include 
 * 1) include 

void main( void ) {  HFILE OsFileHandle; FILE *stream; int CrtFileHandle; OFSTRUCT Buffer; int count = 0; char inbuf[128];

if ( (OsFileHandle = OpenFile("test.dat", &Buffer, OF_READ))== -1){ printf( "OpenFile Failed"); exit(1); }

/* convert OS file handle to CRT file pointer */

if ( (CrtFileHandle=_open_osfhandle(OsFileHandle,_O_RDONLY))==-1){ printf( "_open_osfhandle Failed"); exit(1); }

/* Change handle access to stream access. */   if( (stream = _fdopen( CrtFileHandle, "r" )) == NULL ) { printf( "_fdopen Failed"); exit( 1 ); }

while( fgets( inbuf, 128, stream ) != NULL ) count++;

/* After _fdopen, close with fclose */ fclose( stream ); printf( "Lines in file: %d\n", count ); }

Additional query words: Windows 95

Keywords: kbinfo kbcrt kbcode KB139640

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.