|< C & Win32 programming 1 | Main | C & Win32 programming 3 >| Site Index | Download |


 

MODULE C1

INTRO TO WIN32 AND C PROGRAMMING 2

 

 

My Training Period:      hours

 

Note:

More working program examples, compiled using Visual C++ .Net (Visual studio .Net 2003).  It is low-level programming and the .Net used is Unmanaged (/clr is not set: Project menu → your_project_name Properties… sub menu → Configuration Properties folder → General subfolder → Used Managed Extension setting set to No).  All programs are in debug mode.  The pre-requirement for this Module are structure, function, pointer and array.

 

Abilities

 

         Able to understand and use the Windows’ Handles and objects.

         Able to find and collect the required and related information about functions of the Win32 APIs from the documentation.

         Able to understand and use the functions in your own functional programs.

 

 

 

Using handles and Basic File Management

 

-      The following sections introduce the functions used in file management.  They include file system, directory and file.

-      The related functions and their information also will be explained.  The purpose actually to show how to collect the needed information in order to build a working program.

-      At the end, program examples will be introduced after the required information has been collected.

-      If you refer to the MSDN documentation, you will encounter a lot of the cross references.  Note that how the information is collected from the documentation.

 

Creating, Deleting, and Maintaining Files

 

-      The file management functions identify files and directories by their names.  These functions use the current directory on the current disk drive, unless the name explicitly specifies a path to a different directory, disk drive, or both.

 

Naming a File

 

-      Although each file system can have specific rules about the formation of individual components in a directory or file name, all file systems follow the same general conventions: a base file name and an optional extension, separated by a period.

-      For example, the MS-DOS FAT file system supports 8 characters for the base file name and 3 characters for the extension known as an 8.3 file name.

-      The FAT file system and NTFS are not limited to 8.3 file names; they support long file names.

 

Naming Conventions

 

-      The following rules enable applications to create and process valid names for files and directories regardless of the file system in use:

 

     Use a period (.) to separate the base file name from the extension in a directory name or file name.

     Backslashes (\) are used to separate components in paths (dividing the file name from the path to it, or directories from one another in a path). You cannot use them in file or directory names, however, they may be required as part of volume names.  For example, "C:\".  Note that UNC names must adhere to the following format: \\<server>\<share>.

     Use any character in the current code page for a name, except characters in the range 0 through 31 or any character explicitly disallowed by the file system.  A name can contain characters in the extended character set (128–255).  However, it cannot contain the following reserved characters: <, >, :, ", /, \ and |.

     The following reserved device names cannot be used as the name of a file: CON, PRN, AUX, CLOCK$, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9.  Also avoid these names followed by an extension (for example, NUL.txt).

     Do not assume case sensitivity.  Consider names such as TEST, Test, and test to be the same.

     Do not end a file or directory name with a trailing space or a period.  Although the underlying file system may support such names, the operating system does not.

     Use a period (.) as a directory component in a path to represent the current directory.

     Use two consecutive periods (..) as a directory component in a path to represent the parent of the current directory.

 

Maximum Path Length

 

-      In the Windows API, the maximum length for a path is MAX_PATH, which is defined as 260 characters.

-      A path is structured as follows: drive letter, colon, backslash, components separated by backslashes, and a null-terminating character.

-      For example, the maximum path on the C drive is C:\<256 chars>NULL.

-      The Unicode versions of several functions permit a maximum path length of 32,767 characters, composed of components up to 255 characters in length.

-      To specify such a path, use the "\\?\" prefix.  For example:

 

\\?\D:\<path>

 

-      To specify such a UNC path, use the "\\?\UNC\" prefix.  For example:

 

\\?\UNC\<server>\<share>

 

-      Note that these prefixes are not used as part of the path itself.  They indicate that the path should be passed to the system with minimal modification.  An implication of this is that you cannot use forward slashes to represent path separators or a period to represent the current directory.

-      When using the API to create a directory, the specified path cannot be so long that you could not append an 8.3 file name.

-      Note that the shell and the file system may have different requirements.  It may be possible to create a path with the API that the shell UI cannot handle.

 

Relative Paths

 

-      For functions that manipulate files, the file names may be relative to the current directory.  A file name is relative to the current directory if it does not begin with a disk designator or directory name separator, such as a backslash (\).  If the file name begins with a disk designator, it is a full path.

 

Short and Long File Names

 

-      Windows stores the long file names on disk as special directory entries.  When you create a long file name, Windows also creates the short MS-DOS (8.3) form of the name.

-      To get an MS-DOS file name given a long file name, use the GetShortPathName() function.  To get the full path of a file, use the GetFullPathName() function.

-      The following Table lists the information needed in order to use the GetShortPathName() function.

 

Information

Description

The function

GetShortPathName().

The use

Retrieves the short path form of the specified path.

The prototype

DWORD GetShortPathName(
  LPCTSTR lpszLongPath,
  LPTSTR lpszShortPath,
  DWORD cchBuffer);

Example

char szlongpath[100] = "C:\\Documents and Settings\\All Users";

char szshortpath[100];

char buffer = 100;

 

GetShortPathName(

  szlongpath,

  szshortpath,

  buffer

);

The parameters

lpszLongPath

[in] Pointer to a null-terminated path string.  The function retrieves the short form of this path.

In the ANSI version of this function, the name is limited to MAX_PATH characters.  To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path.

 

lpszShortPath

[out] Pointer to a buffer to receive the null-terminated short form of the path specified by lpszLongPath.

 

cchBuffer

[in] Size of the buffer pointed to by lpszShortPath, in TCHARs.

The return value

If the function succeeds, the return value is the length, in TCHARs, of the string copied to lpszShortPath, not including the terminating null character.

If the lpszShortPath buffer is too small to contain the path, the return value is the size of the buffer, in TCHARs, required to hold the path.  Therefore, if the return value is greater than cchBuffer, call the function again with a buffer that is large enough to hold the path.

If the function fails for any other reason, the return value is zero. To get extended error information, call GetLastError().

The header file

<windows.h>

 

Table 13:  GetShortPathName() information.

 

-      The following example uses GetShortPathName() function to get the path name (and file name) in MS_DOS format for a given long name.

 

#include <windows.h>

#include <stdio.h>

 

char szlongpath[100] = "C:\\Documents and Settings\\All Users";

char szshortpath[100];

char buffer = 100;

 

int main()

{

       DWORD test = GetShortPathName(

              szlongpath,

              szshortpath,

              buffer

);

 

printf("The long path name   = %s, the error is %d\n", szlongpath, GetLastError());

printf("The short path name  = %s, the error is %d\n", szshortpath, GetLastError());

printf("The length in TCHARs = %d, the error is %d\n", test, GetLastError());

 

return 0;

}

 

The output:

 

The long path name   = C:\Documents and Settings\All Users, the error is 0

The short path name  = C:\DOCUME~1\ALLUSE~1, the error is 0

The length in TCHARs = 20, the error is 0

Press any key to continue

 

-      The following Table lists the information needed in order to use the GetFullPathName() function.

 

Information

Description

The function

GetFullPathName().

The use

Retrieves the full path and file name of the specified file.

The prototype

DWORD GetFullPathName(
  LPCTSTR lpFileName,
  DWORD nBufferLength,
  LPTSTR lpBuffer,
  LPTSTR* lpFilePart);

Example

char lpFileName[20] = "module20.txt";

char lpBuffer[50];

LPSTR *lpFilePart = NULL;

 

GetFullPathName(

  lpFileName,

  100,

  lpBuffer,

  lpFilePart);

The parameters

lpFileName

[in] Pointer to a null-terminated string that specifies a valid file name.  This string can use either short (the 8.3 form) or long file names;

 

nBufferLength

[in] Size of the buffer to receive the null-terminated string for the drive and path, in TCHARs.

 

lpBuffer

[out] Pointer to a buffer that receives the null-terminated string for the drive and path.

 

lpFilePart

[out] Pointer to a buffer that receives the address (in lpBuffer) of the final file name component in the path.

The return value

If the function succeeds, the return value is the length of the string copied to lpBuffer, not including the terminating null character, in TCHARs.

If the lpBuffer buffer is too small to contain the path, the return value is the size of the buffer required to hold the path plus the terminating null character, in TCHARs.  Therefore, if the return value is greater than nBufferLength, call the function again with a buffer that is large enough to hold the path.

If the function fails for any other reason, the return value is zero. To get extended error information, call GetLastError().

The header file

<windows.h>

 

Table 14:  GetFullPathName() information.

 

-      The following example uses GetFullPathName() function to get the full path for a given file name.

 

#include <windows.h>

#include <stdio.h>

 

int main()

{

char lpFileName[20] = "module20.txt";

char lpBuffer[50];

LPSTR *lpFilePart = NULL;

 

DWORD test = GetFullPathName(

  lpFileName,

  100,

  lpBuffer,

  lpFilePart);

 

printf("The %s\'s path is %s.\n", lpFileName, lpBuffer);

return 0;

}

 

The output:

 

The module20.txt's path is g:\vcnetprojek\win32prog\module20.txt.

Press any key to continue

 

-      Windows stores the long file names on disk in Unicode.  This means that the original long file name is always preserved, even if it contains extended characters, and regardless of the code page that is active during a disk read or write operation.

-      The case of the file name is preserved, but the file system is not case-sensitive.

-      The valid character set for these long file names is the NTFS character set, less one character: the colon (:) that NTFS uses for opening alternate file streams.

-      This means that you can freely copy files between NTFS and FAT partitions without losing any file name information.

 

Creating and Opening Files – Collecting the Information

 

-      Now, let have some stories about the CreateFile() function.  If you compare with the create file function of the C run-time (CRT), Win32 version is quite complex but more functionalities.

-      This function can be used to create or open a file, directory, physical disk, volume, console buffer, tape drive, communications resource, mailslot, or named pipe.

-      The function returns a handle that can be used to access the object.

 

The prototype

 

HANDLE CreateFile(
  LPCTSTR lpFileName,
  DWORD dwDesiredAccess,
  DWORD dwShareMode,
  LPSECURITY_ATTRIBUTES lpSecurityAttributes,
  DWORD dwCreationDisposition,
  DWORD dwFlagsAndAttributes,
  HANDLE hTemplateFile);

 

-      Using CreateFile() to open an existing file for reading example.  The file is already existed at the root.

// For Win Xp Pro
#define _WIN32_WINNT 0x0501
#include <windows.h>
#include <stdio.h>

HANDLE hFile;
char fname[30] = "C:\\testfile.txt";

int main()
{
  // Open the file handle
  hFile = CreateFile("C:\\testfile.txt", // file to open
                  GENERIC_READ,          // open for reading
                  FILE_SHARE_READ,       // share for reading
                  NULL,                  // default security
                  OPEN_EXISTING,         // existing file only
                  FILE_ATTRIBUTE_NORMAL, // normal file
                  NULL);                 // no attribute template

// Verify...
if(hFile == INVALID_HANDLE_VALUE)
  printf("Could not open %s file, error %d.\n", fname, GetLastError());
else
  printf("%s opened successfully.\n", fname);

// Close the handle
if(CloseHandle(hFile) != 0)
  printf("%s file closed successfully.\n", fname);
else
  printf("Something wrong, cannot close %s file lol! error %u\n", fname, GetLastError());
return 0;
}
 

C:\testfile.txt opened successfully.
C:\testfile.txt file closed successfully.
Press any key to continue

-      Using CreateFile() to create a new file and opens it for writing example.

// For Win Xp Pro
#define _WIN32_WINNT 0x0501
#include <windows.h>
#include <stdio.h>

int main()
{
  HANDLE hFile;
  char fname[30] = "C:\\testfile.txt";

  hFile = CreateFile(fname,         // file to create
            GENERIC_WRITE,          // open for writing
            0,                      // do not share
            NULL,                   // default security
            CREATE_ALWAYS,          // overwrite existing
            FILE_ATTRIBUTE_NORMAL | // normal file
            FILE_FLAG_OVERLAPPED,   // asynchronous I/O
            NULL);                  // no attribute template

if(hFile == INVALID_HANDLE_VALUE)
  printf("Could not open %s file, error %u.\n", fname, GetLastError());
else
  printf("%s file created successfully, error if any, %u.\n", fname, GetLastError());
 

  return 0;
}

 

C:\testfile.txt file created successfully, error if any, 0.
Press any key to continue

The Parameters

 

 

lpFileName

[in] Pointer to a null-terminated string that specifies the name of the object to create or open.

In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. 

 

dwDesiredAccess

[in] Access to the object (reading, writing, or both).  You cannot request an access mode that conflicts with the sharing mode specified in a previous open request whose handle is still open.

If this parameter is zero, the application can query file and device attributes without accessing the device.  This is useful if an application wants to determine the size of a floppy disk drive and the formats it supports without requiring a floppy in the drive.  It can also be used to test for the file's or directory's existence without opening it for read or writes access.

 

dwShareMode

[in] Sharing mode of the object (reading, writing, both, or neither). You cannot request a sharing mode that conflicts with the access mode specified in a previous open request whose handle is still open. Doing so would result in a sharing violation (ERROR_SHARING_VIOLATION).

If this parameter is zero and CreateFile() succeeds, the object cannot be shared and cannot be opened again until the handle is closed.

To enable other processes to share the object while your process has it open, use a combination of one or more of the following values to specify the access mode they can request when they open the object. These sharing options remain in effect until you close the handle to the object.

 

Value

Meaning

FILE_SHARE_DELETE

Enables subsequent open operations on the object to request delete access.  Otherwise, other processes cannot open the object if they request delete access.

FILE_SHARE_READ

Enables subsequent open operations on the object to request read access.  Otherwise, other processes cannot open the object if they request read access.

FILE_SHARE_WRITE

Enables subsequent open operations on the object to request write access.  Otherwise, other processes cannot open the object if they request write access.

 

Table 15:  dwShareMode values.

 

lpSecurityAttributes

[in] Pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If lpSecurityAttributes is NULL, the handle cannot be inherited.

The lpSecurityDescriptor member of the structure specifies a security descriptor for the object. If lpSecurityAttributes is NULL, the object gets a default security descriptor.  The Access Control Lists (ACLs) in the default security descriptor for a file or directory are inherited from its parent directory.  Note that the target file system must support security on files and directories for this parameter to have an effect on them.

 

dwCreationDisposition

[in] Action to take on files that exist, and which action to take when files do not exist.  This parameter must be one of the following values.

 

Value

Meaning

CREATE_ALWAYS

Creates a new file.  If the file exists, the function overwrites the file, clears the existing attributes, combines the specified file attributes and flags with FILE_ATTRIBUTE_ARCHIVE, but does not set the security descriptor specified by the SECURITY_ATTRIBUTES structure.

CREATE_NEW

Creates a new file. The function fails if the specified file already exists.

OPEN_ALWAYS

Opens the file, if it exists.  If the file does not exist, the function creates the file as if dwCreationDisposition were CREATE_NEW.

OPEN_EXISTING

Opens the file. The function fails if the file does not exist.

You should use OPEN_EXISTING for devices.

TRUNCATE_EXISTING

Opens the file and truncates it so that its size is zero bytes. The calling process must open the file with the GENERIC_WRITE access right. The function fails if the file does not exist.

 

Table 16:  dwCreationDisposition values.

 

dwFlagsAndAttributes

[in] File attributes and flags.

The following file attributes and flags are used only for file objects, not other types of objects created by CreateFile().  When CreateFile() opens an existing file, it combines the file flags with existing file attributes, and ignores any supplied file attributes.

This parameter can include any combination of the file attributes (noting that all other file attributes override FILE_ATTRIBUTE_NORMAL).

 

Attribute

Meaning

FILE_ATTRIBUTE_ARCHIVE

The file should be archived.  Applications use this attribute to mark files for backup or removal.

FILE_ATTRIBUTE_ENCRYPTED

The file or directory is encrypted.  For a file, this means that all data in the file is encrypted.  For a directory, this means that encryption is the default for newly created files and subdirectories.

This flag has no effect if FILE_ATTRIBUTE_SYSTEM is also specified.

FILE_ATTRIBUTE_HIDDEN

The file is hidden.  It is not to be included in an ordinary directory listing.

FILE_ATTRIBUTE_NORMAL

The file has no other attributes set.  This attribute is valid only if used alone.

FILE_ATTRIBUTE_NOT_CONTENT_INDEXED

The file will not be indexed by the content indexing service.

FILE_ATTRIBUTE_OFFLINE

The data of the file is not immediately available.  This attribute indicates that the file data has been physically moved to offline storage.  This attribute is used by Remote Storage, the hierarchical storage management software.  Applications should not arbitrarily change this attribute.

FILE_ATTRIBUTE_READONLY

The file is read only.  Applications can read the file but cannot write to it or delete it.

FILE_ATTRIBUTE_SYSTEM

The file is part of or is used exclusively by the operating system.

FILE_ATTRIBUTE_TEMPORARY

The file is being used for temporary storage.  File systems avoid writing data back to mass storage if sufficient cache memory is available, because often the application deletes the temporary file shortly after the handle is closed.  In that case, the system can entirely avoid writing the data.  Otherwise, the data will be written after the handle is closed.

 

Table 17:  dwFlagsAndAttributes values.

 

-      This parameter can also include any combination of the following flags.

 

Flag

Meaning

FILE_FLAG_BACKUP_SEMANTICS

The file is being opened or created for a backup or restore operation.  The system ensures that the calling process overrides file security checks, provided it has the SE_BACKUP_NAME and SE_RESTORE_NAME privileges.

You can also set this flag to obtain a handle to a directory. Where indicated, a directory handle can be passed to some functions in place of a file handle.

FILE_FLAG_DELETE_ON_CLOSE

The system is to delete the file immediately after all of its handles have been closed, not just the specified handle but also any other open or duplicated handles.

If there are existing open handles to the file, the call fails unless they were all opened with the FILE_SHARE_DELETE share mode.  Subsequent open requests for the file will fail, unless they specify the FILE_SHARE_DELETE share mode.

FILE_FLAG_NO_BUFFERING

The system is to open the file with no system caching.  This flag has no effect on hard disk caching.  When combined with FILE_FLAG_OVERLAPPED, the flag gives maximum asynchronous performance, because the I/O does not rely on the synchronous operations of the memory manager.  However, some I/O operations will take longer, because data is not being held in the cache.  Also, the file metadata may still be cached. To flush the metadata to disk, use the FlushFileBuffers() function.

An application must meet certain requirements when working with files opened with FILE_FLAG_NO_BUFFERING:

     File access must begin at byte offsets within the file that are integer multiples of the volume's sector size.

     File access must be for numbers of bytes that are integer multiples of the volume's sector size.  For example, if the sector size is 512 bytes, an application can request reads and writes of 512, 1024, or 2048 bytes, but not of 335, 981, or 7171 bytes.

     Buffer addresses for read and write operations should be sector aligned (aligned on addresses in memory that are integer multiples of the volume's sector size). Depending on the disk, this requirement may not be enforced.

One way to align buffers on integer multiples of the volume sector size is to use VirtualAlloc() to allocate the buffers. It allocates memory that is aligned on addresses that are integer multiples of the operating system's memory page size.  Because both memory page and volume sector sizes are powers of 2, this memory is also aligned on addresses that are integer multiples of a volume's sector size.  An application can determine a volume's sector size by calling the GetDiskFreeSpace() function.

FILE_FLAG_OPEN_NO_RECALL

The file data is requested, but it should continue to reside in remote storage.  It should not be transported back to local storage.  This flag is intended for use by remote storage systems.

FILE_FLAG_OPEN_REPARSE_POINT

The system is to inhibit the reparse behavior of NTFS reparse points.  When the file is opened, a file handle is returned, whether the filter that controls the reparse point is operational or not.  This flag cannot be used with the CREATE_ALWAYS flag.

FILE_FLAG_OVERLAPPED

The file is being opened or created for asynchronous I/O.  When the operation is finished, the event specified to the call in the OVERLAPPED structure is set to the signaled state.  Operations that take a significant amount of time to process return ERROR_IO_PENDING.

If this flag is specified, the file can be used for simultaneous read and write operations.  The system does not maintain the file pointer.  Therefore you must pass the file position to the read and write functions in the OVERLAPPED structure or update the file pointer.  If this flag is not specified, then I/O operations are serialized, even if the calls to the read and write functions specify an OVERLAPPED structure.

FILE_FLAG_POSIX_SEMANTICS

Indicates that the file is to be accessed according to POSIX rules.  This includes allowing multiple files with names, differing only in case, for file systems that support such naming.  Use care when using this option because files created with this flag may not be accessible by applications written for MS-DOS or 16-bit Windows.

FILE_FLAG_RANDOM_ACCESS

Indicates that the file is accessed randomly.  The system can use this as a hint to optimize file caching.

FILE_FLAG_SEQUENTIAL_SCAN

Indicates that the file is to be accessed sequentially from beginning to end.  The system can use this as a hint to optimize file caching.  If an application moves the file pointer for random access, optimum caching may not occur; however, correct operation is still guaranteed.

Specifying this flag can increase performance for applications that read large files using sequential access.  Performance gains can be even more noticeable for applications that read large files mostly sequentially, but occasionally skip over small ranges of bytes.

FILE_FLAG_WRITE_THROUGH

Instructs the system to write through any intermediate cache and go directly to disk.

If FILE_FLAG_NO_BUFFERING is not also specified, so that system caching is in effect, then the data is written to the system cache, but is flushed to disk without delay.

If FILE_FLAG_NO_BUFFERING is also specified, so that system caching is not in effect, then the data is immediately flushed to disk without going through the system cache.  The operating system also requests a write-through the hard disk cache to persistent media.  However, not all hardware supports this write-through capability.

 

Table 18:  dwFlagsAndAttributes extension values.

 

-      If the CreateFile() function opens the client side of a named pipe, the dwFlagsAndAttributes parameter can also contain Security Quality of Service information.

-      When the calling application specifies the SECURITY_SQOS_PRESENT flag, the dwFlagsAndAttributes parameter can contain one or more of the following values.

 

Value

Meaning

SECURITY_ANONYMOUS

Impersonate the client at the Anonymous impersonation level.

SECURITY_CONTEXT_TRACKING

The security tracking mode is dynamic.  If this flag is not specified, the security tracking mode is static.

SECURITY_DELEGATION

Impersonate the client at the Delegation impersonation level.

SECURITY_EFFECTIVE_ONLY

Only the enabled aspects of the client's security context are available to the server.  If you do not specify this flag, all aspects of the client's security context are available.

This allows the client to limit the groups and privileges that a server can use while impersonating the client.

SECURITY_IDENTIFICATION

Impersonate the client at the Identification impersonation level.

SECURITY_IMPERSONATION

Impersonate the client at the Impersonation impersonation level.

 

Table 19:  dwFlagsAndAttributes for SECURITY_SQOS_PRESENT flag.

 

hTemplateFile

[in] Handle to a template file, with the GENERIC_READ access right.  The template file supplies file attributes and extended attributes for the file being created.  This parameter can be NULL.

If opening an existing file, CreateFile() ignores the template file.

 

The Return Values

 

-      If the function succeeds, the return value is an open handle to the specified file.

-      If the specified file exists before the function call and dwCreationDisposition() is CREATE_ALWAYS or OPEN_ALWAYS, a call to GetLastError() returns ERROR_ALREADY_EXISTS (even though the function has succeeded).  If the file does not exist before the call, GetLastError() returns zero.

-      If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError().

-      Use the CloseHandle() function to close an object handle returned by CreateFile().

-      Some file systems, such as NTFS, support compression or encryption for individual files and directories. On volumes formatted for such a file system, a new file inherits the compression and encryption attributes of its directory.

-      You cannot use CreateFile() to control compression on a file or directory.

 

Files

 

-      If you are attempting to create a file on a floppy drive that does not have a floppy disk or a CD-ROM drive that does not have a CD, the system displays a message box asking the user to insert a disk or a CD, respectively.

-      To prevent the system from displaying this message box, call the SetErrorMode() function with SEM_FAILCRITICALERRORS.

-      If you rename or delete a file, then restore it shortly thereafter, the system searches the cache for file information to restore.  Cached information includes its short/long name pair and creation time.

-      If you call CreateFile() on a file that is pending deletion as a result of a previous call to DeleteFile(), the function fails.

-      The operating system delays file deletion until all handles to the file are closed. GetLastError() returns ERROR_ACCESS_DENIED.

-      When an application creates a file across the network, it is better to use GENERIC_READ | GENERIC_WRITE than to use GENERIC_WRITE alone.

-      The resulting code will be faster because the redirector can use the cache manager and send fewer SMBs with more data.  This combination also avoids an issue where writing to the file across the network can occasionally return ERROR_ACCESS_DENIED.

 

Directories

 

-      An application cannot create a directory with CreateFile(); it must call CreateDirectory() or CreateDirectoryEx() to create a directory.

-      Opening a directory with CreateFile() requires the FILE_FLAG_BACKUP_SEMANTICS flag.

 

Physical Disks and Volumes

 

-      You can use the CreateFile() function to open a physical disk drive or a volume.  The function returns a handle that can be used with the DeviceIoControl() function.

-      This enables you to access the disk's partition table.  It is potentially dangerous to do so, since an incorrect write to a disk could make its contents inaccessible.

-      The following requirements must be met for such a call to succeed:

 

     The caller must have administrative privileges.

     The dwCreationDisposition parameter must have the OPEN_EXISTING flag.

     When opening a volume or floppy disk, the dwShareMode parameter must have the FILE_SHARE_WRITE flag.

 

-      When opening a physical drive, x, the lpFileName string should be of the form \\.\PHYSICALDRIVE<x>.

-      Hard disk numbers start at zero.  The following table shows some example physical drive strings.

 

String

Meaning

\\.\PHYSICALDRIVE0

Opens the first physical drive.

\\.\PHYSICALDRIVE2

Opens the third physical drive.

 

Table 20.

 

-      When opening a volume or floppy drive, the lpFileName string should be of the form \\.\<x>:.

-      Do not use a trailing backslash.  This would indicate the root directory of the drive.  The following table shows some example drive strings.

 

String

Meaning

\\.\A:

Opens drive A (floppy drive).

\\.\C:

Opens drive C (volume).

 

Table 21.

 

-      You can also open a volume by referring to its volume name.  Volume handles may be opened as noncached at the discretion of the file system, even when the noncached option is not specified with CreateFile().

-      You should assume that all Microsoft file systems open volume handles as noncached.  The restrictions on noncached I/O for files apply to volumes as well.

-      A file system may or may not require buffer alignment even though the data is noncached.  However, if the noncached option is specified when opening a volume, buffer alignment is enforced regardless of the file system on the volume.

-      It is recommended on all file systems that you open volume handles as noncached and follow the noncached I/O restrictions.

 

Tape Drives

 

-      You can open tape drives using a file name of the form \\.\TAPE<x> where <x> is a number indicating which drive to open, starting with tape drive 0.

-      To open tape drive 0 in an application written in C or C++, use the file name "\\\\.\\TAPE0".

 

Communications Resources

 

-      The CreateFile() function can create a handle to a communications resource, such as the serial port COM1.

-      For communications resources, the dwCreationDisposition parameter must be OPEN_EXISTING, and the hTemplate parameter must be NULL.

-      Read, write, or read/write access can be specified, and the handle can be opened for overlapped I/O.

 

Consoles

 

-      The CreateFile() function can create a handle to console input (CONIN$).

-      If the process has an open handle to it as a result of inheritance or duplication, it can also create a handle to the active screen buffer (CONOUT$).

-      The calling process must be attached to an inherited console or one allocated by the AllocConsole() function.

-      For console handles, set the CreateFile() parameters as follows.

 

Parameters

Value

lpFileName

Use the CONIN$ value to specify console input and the CONOUT$ value to specify console output.

CONIN$ gets a handle to the console's input buffer, even if the SetStdHandle() function redirected the standard input handle. To get the standard input handle, use the GetStdHandle() function.

CONOUT$ gets a handle to the active screen buffer, even if SetStdHandle() redirected the standard output handle. To get the standard output handle, use GetStdHandle().

dwDesiredAccess

GENERIC_READ | GENERIC_WRITE is preferred, but either one can limit access.

dwShareMode

When opening CONIN$, be sure to specify FILE_SHARE_READ.  When opening CONOUT$, be sure to specify FILE_SHARE_WRITE.

If the calling process inherited the console or if a child process should be able to access the console, this parameter must be FILE_SHARE_READ | FILE_SHARE_WRITE.