File Operations

Under Windows 3.x, the usual method of opening and closing a file consists of calling the same fopen and fclose procedures used under DOS:

   hFil = fopen( szFName, “r+b” );                  // 3.x
   if( hFil != -1 )
   {
      FilSz = filelength( fileno( hFil ) );
      ...
      fclose( hFil );
   }

In addition to opening and closing the file in this fragmentary example, the filelength function is also invoked to return the file size. This also should be a familiar function both from Windows 3.1 and from DOS applications, but it changes almost beyond recognition in its Windows 98/95/NT counterpart.

In the Windows 98/95/NT revision, which follows, very little has remained the same. The hFil variable is still used to retrieve a handle to the file opened, but virtually everything else is different.

   hFil = OpenFile( szFName, &FileBuff,             // 98/95/NT
                    OF_CANCEL | OF_PROMPT | OF_READ );
   if( hFil != -1 )
   {
      FilSz = GetFileSize( (HANDLE) hFil, &FilSzHigh );
      ...
      _lclose( hFil );
   }

As you can see, the fopen procedure has been replaced by the OpenFile API call, which uses a quite different selection of parameters. One of these parameters is a pointer to the FileBuff structure, which receives information about the file.

The GetFileSize function is also a major change from its predecessor, filelength. Instead of returning a long value with the file size in bytes, GetFileSize returns two DWORD values: FilSz and FilSzHigh. The reason for this particular change is simple: A signed long value can only report a file size up to about 2GB, but a signed double DWORD value (64 bits) can handle really large file sizes—up to 1.7 × 10308 bytes. Granted, it may be a year or two before mass-storage facilities provide any real need for reporting files of such size, but it will happen eventually.

The final difference—changing fclose to _lclose—is almost no change at all.

NOTE

There is no CloseFile instruction corresponding to the OpenFile API. Instead, the _lclose function is normally used to close a file.

Alternately, instead of using the _lclose instruction, the CloseHandle function can also be used to close files:

   hFil = OpenFile( szFName, &FileBuff,             // 98/95/NT
                    OF_CANCEL | OF_PROMPT | OF_READ );
   if( hFil != -1 )
   {
      FilSz = GetFileSize( (HANDLE) hFil, &FilSzHigh );
      ...
      CloseHandle( hFil );
   }

But opening and closing files are only one aspect of file operations. The previously familiar directory operations have also changed, although perhaps not as drastically.

© 1998 SYBEX Inc. All rights reserved.