|< C & Win32 programming 7 | Main | ANSI, Multi-byte, Unicode and Localization 1 >|Site Index |Download |


 

 

 

 

MODULE F1

WIN32 AND C PROGRAMMING 8

 

 

 

 

What are in this Module?

  1. Mounting And Unmounting Volume

  2. Program Examples

  3. Volume Management Functions

  4. File Management: File Management Functions

  5. File Management Control Codes

  6. File Management Structures

  7. File Management Enumeration Types

 

 

My Training Period: xx hours. Before you begin, read someinstruction here.

 

 

 

 

 

 

 

 

 

 

Abilities that supposed to be acquired:

 

  • Be familiar and play around with the Win32 programming.

  • Able to find and collect information about volume management functions.

  • Able to understand and use the collected information about the functions in programs.

Mounting And Unmounting Volume

  • Mounting a volume is a two-step process:

  1. Call GetVolumeNameForVolumeMountPoint() with the DOS drive letter of the volume you want to mount.

  2. Then use the returned unique volume name and the directory where you want to mount the volume in a call toSetVolumeMountPoint().

  • Your application can designate any directory on a volume other than the root as a volume mount point. Instead of making the root directory a volume mount point, your application should create a subdirectory and make that a volume mount point.

  • When a volume is mounted, volume mount points see the drive, not the medium in the drive.  Thus, you need not unmount and mount volumes to change removable media.

  • You can set multiple volume mount points to see the same physical drive.  For example, you might have a volume mount point for each of several compact discs, all of which share one CD-ROM drive.

  • Each point refers to the same physical CD-ROM drive, and you can access any disc in the drive from any of the volume mount points.  The advantage of setting multiple volume mount points is that the different paths make clear the difference between different CDs' applications, for example between a word processor and a game.

  • If a volume fails, paths that cross the failed drive break. Thus, it is best to mount all volumes to the boot drive (usually drive C).  It is a useful mnemonic for system administrators to use one directory as the volume mount point for all volumes on the system, but nothing in the volume mount point design requires that you use only one directory.

  • A volume mount point is a directory where a volume can be mounted but not necessarily where a volume currently is mounted.

  • NTFS file system volume mount points are implemented by using reparse points and are subject to their restrictions.

  • It is not necessary to manipulate reparse points in order to use volume mount points; the volume mount point functions handle all the reparse point details for you.

  • Because volume mount points are directories, you can rename, remove, move, and otherwise manipulate them, like you can with directories.

  • Only NTFS file system volumes can hold a volume mount point, although any local drive can be mounted on one.

  • It is not an error to attempt to mount a volume at a volume mount point at which a volume is already mounted.  In this case, the system unmounts the preceding volume without sending notifications before attempting to mount the new volume.

  • It is an error to attempt to mount a volume on a directory that has any files or subdirectories in it.  This error occurs for system and hidden directories as well as other directories, and it occurs for system and hidden files.

  • When mount points are created in a clustered drive, they may be unexpectedly deleted under certain circumstances.

  • The following Table lists the needed information in order to use the GetVolumeNameForVolumeMountPoint() function.

 

Information

Description

The function

GetVolumeNameForVolumeMountPoint().

The use

Takes a volume mount point or root directory and returns the corresponding unique volume name.

The prototype

BOOL GetVolumeNameForVolumeMountPoint( LPCTSTR lpszVolumeMountPoint, LPTSTR lpszVolumeName,
 DWORD cchBufferLength);

Example

#define BUFSIZE MAX_PATH

 

char Buf[BUFSIZE];

 

GetVolumeNameForVolumeMountPoint(

argv[2],       // input volume mount point or directory

Buf,            // output volume name buffer

BUFSIZE); // size of volume name buffer

The parameters

lpszVolumeMountPoint - [in] Pointer to a string that contains either the path of a volume mount point with a trailing backslash (\) or a drive letter indicating a root directory in the form "D:\".

lpszVolumeName - [out] Pointer to a string that receives the volume name. This name is a unique volume name of the form "\\?\Volume{GUID}\" whereGUID is the GUID that identifies the volume.

cchBufferLength - [in] Length of the output buffer, inTCHARs.  A reasonable size for the buffer to accommodate the largest possible volume name is 50 characters.

The return value

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.  To get extended error information, callGetLastError().

The header file

<windows.h>

 

Table 9:  GetVolumeNameForVolumeMountPoint() information.

Information

Description

The function

SetVolumeMountPoint().

The use

Mounts the specified volume at the specified volume mount point.

The prototype

BOOL SetVolumeMountPoint( LPCTSTR lpszVolumeMountPoint, LPCTSTR lpszVolumeName );

Example

char Buf[BUFSIZE];

 

SetVolumeMountPoint(

argv[1],    // mount point

Buf);        // volume to be mounted

The parameters

lpszVolumeMountPoint -  [in] Pointer to a string that indicates the volume mount point where the volume is to be mounted.  This may be a root directory (X:\) or a directory on a volume (X:\mnt\).  The string must end with a trailing backslash ('\').

 

lpszVolumeName - [in] Pointer to a string that indicates the volume to be mounted. This string must be a unique volume name of the form "\\?\Volume{GUID}\" where GUID is a GUID that identifies the volume.  The\\?\ turns off path parsing and is ignored as part of the path. For example,"\\?\C:\myworld\private" is seen as "C:\myworld\private".

The return value

If the function succeeds, the return value is nonzero.  If the function fails, the return value is zero.  To get extended error information, callGetLastError().

The header file

<windows.h>

 

Table10:  SetVolumeMountPoint() information.

"C:\Mnt\Ddrive\Mnt\Edrive\Dir\Subdir\MyFile.txt"

Information

Description

The function

GetVolumePathName().

The use

Retrieves the volume mount point at which the specified path is mounted.

The prototype

BOOL GetVolumePathName( LPCTSTR lpszFileName, LPTSTR lpszVolumePathName, DWORD cchBufferLength);

Example

char lpszFileName[100] = "F:\\...\\...";

char lpszVolumePathName[100];

DWORD cchBufferLength = 100;

 

GetVolumePathName(

  lpszFileName,

  lpszVolumePathName,

  cchBufferLength);

The parameters

lpszFileName - [in] Pointer to the input path string.  Both absolute and relative file and directory names, such as ".", are acceptable in this path.

lpszVolumePathName - [out] Pointer to a string that receives the volume mount point for the input path.

cchBufferLength - [in] Length of the output buffer, inTCHARs.

The return value

If the function succeeds, the return value is nonzero.  If the function fails, the return value is zero.  To get extended error information, callGetLastError().

The header file

<windows.h>

 

Table 11:  GetVolumePathName() information.

 

//*********mymount.cpp************

// you need to change the path used in this program to yours

#define _WIN32_WINNT 0x0501

#include <windows.h>

#include <stdio.h>

#define BUFSIZE MAX_PATH

 

int main(int argc, char *argv[ ])

{

BOOL bFlag;

// temporary buffer for volume name

char Buf[BUFSIZE];

// If not enough arguments supplied...for this example you have to create the mount point first

if(argc != 3)

{

    printf("\"%s\" command mounts a volume at a mount point.\n", argv[0]);

    printf("Usage: %s <mount point> <volume to be mounted>\n", argv[0]);

    printf("And make sure the <mount point> exists!!!\n", argv[0]);

    printf("Example: \"%s c:\\mymnt\\gdrive\\ g:\\\"\n", argv[0]);

    // just exit

    return(-1);

}

 

    // some verification, check the inputs validity

    bFlag = GetVolumeNameForVolumeMountPoint(

              argv[2],         // input volume mount point or directory

                  Buf,           // output volume name buffer

               BUFSIZE    // size of volume name buffer

           );

 

    if(bFlag != TRUE)

    {

        printf("Retrieving volume name for %s failed.\n", argv[2]);

        // just exit

        return (-2);

    }

    printf("Volume name of %s is %s\n", argv[2], Buf);

    bFlag = SetVolumeMountPoint(

              argv[1],       // mount point

                  Buf);        // volume to be mounted

    // another verification, error checking

    if(!bFlag)

        printf("Attempt to mount %s at %s failed.\n", argv[2], argv[1]);

    else

    {

        printf("%s is successfully mounted at %s\n", argv[2], argv[1]);

        char lpszFileName[100] = "F:\\mymntpoint\\projectc\\doc\\Borland.doc";

        char lpszVolumePathName[100];

        DWORD cchBufferLength = 100;

        BOOL test = GetVolumePathName( lpszFileName, lpszVolumePathName, cchBufferLength);

        printf("The Volume path name for %s is:\n %s\n", lpszFileName, lpszVolumePathName);

    }

    return (bFlag);

}

 

A sample output:

 

G:\vcnetprojek\mymount\Debug>mymount

"mymount" command mounts a volume at a mount point.

Usage: mymount <mount point> <volume to be mounted>

And make sure the <mount point> exists!!!

Example: "mymount c:\mymnt\gdrive\ g:\"

 

G:\vcnetprojek\mymount\Debug>mymount F:\\mymntpoint\ I:\

Volume name of I:\ is \\?\Volume{a3446edb-ebd9-11d8-a25c-806d6172696f}\

I:\ is successfully mounted at F:\\mymntpoint\

The Volume path name for F:\mymntpoint\projectc\doc\Borland.doc is:

 F:\mymntpoint\

 

G:\vcnetprojek\mymount\Debug>

Windows mount a directory

 

 

Windows directory has been mounted

Information

Description

The function

DeleteVolumeMountPoint().

The use

Unmounts the volume from the specified volume mount point.

The prototype

BOOL DeleteVolumeMountPoint( LPCTSTR lpszVolumeMountPoint );

Example

DeleteVolumeMountPoint(argv[1]);

The parameters

lpszVolumeMountPoint - [in] Pointer to a string that indicates the volume mount point to be unmounted.  This may be a root directory such as X:\, in which case the DOS drive letter assignment is removed or a directory on a volume such asX:\mnt\.  A trailing backslash is required.

The return value

If the function succeeds, the return value is nonzero.  If the function fails, the return value is zero.  To get extended error information, callGetLastError().

The header file

<windows.h>

 

Table 12:  DeleteVolumeMountPoint() information.

//*******myunmount.cpp***********

// change the path used in this program to yours

#define _WIN32_WINNT 0x0501

#include <windows.h>

#include <stdio.h>

 

int main(int argc, char *argv[])

{

BOOL bFlag;

// if the argument for the mount point is not given...

if(argc != 2)

{

  printf("%s command unmounts a volume from the volume mount point.\n", argv[0]);

  printf("Usage: \"%s <the_mount_point>\n", argv[0]);

  printf("Example: \"%s c:\\mymnt\\gdrive\\\"\n", argv[0]);

  // just exit

  return (-1);

}

 

// do some verification, error checking...the argv[1] is a path of the volume mount point

bFlag = DeleteVolumeMountPoint(argv[1]);

 

if(!bFlag)

{

  printf("Unmounting the volume at %s failed!\n", argv[1]);

  exit(-1);

}

else

  printf("Unmounting the volume at %s successfully done!\n", argv[1]);

return (bFlag);

}

 

A sample output:

 

G:\vcnetprojek\mymount\Debug>mymount F:\mymntpoint\ I:\

Volume name of I:\ is \\?\Volume{a3446edb-ebd9-11d8-a25c-806d6172696f}\

I:\ is successfully mounted at F:\mymntpoint\

The Volume path name for F:\mymntpoint\projectc\doc\Borland.doc is:

 F:\mymntpoint\

 

G:\vcnetprojek\mymount\Debug>cd g:\vcnetprojek\myunmount\debug

 

G:\vcnetprojek\myunmount\Debug>myunmount

myunmount command unmounts a volume from the volume mount point.

Usage: "myunmount <the_mount_point>

Example: "myunmount c:\mymnt\gdrive\"

G:\vcnetprojek\myunmount\Debug>myunmount F:\mymntpoint\

Unmounting the volume at F:\mymntpoint\ successfully done!

 

G:\vcnetprojek\myunmount\Debug>

 

Information

Description

The function

GetVolumePathNamesForVolumeName().

The use

Retrieves a list of path names for the specified volume name.

The prototype

BOOL GetVolumePathNamesForVolumeName( LPCTSTR lpszVolumeName, LPTSTR lpszVolumePathNames,
DWORD cchBufferLength,   PDWORD lpcchReturnLength);

The parameters

lpszVolumeName - [in] Pointer to a string that specifies the volume name.

lpszVolumePathNames - [out] Pointer to a buffer that receives the list of volume path names.  The list is an array of null-terminated strings terminated by an additional NULL character.  If the buffer is not large enough to hold the complete list, the buffer holds as much of the list as possible.

cchBufferLength - [in] Length of thelpszVolumePathNames buffer, in TCHARs.

lpcchReturnLength - [out] If the call is successful, this parameter is the number ofTCHARs copied to the lpszVolumePathNames buffer.  Otherwise, this parameter is the size of the buffer required to hold the complete list, inTCHARs.

The return value

If the function succeeds, the return value is nonzero.  If the function fails, the return value is zero.  To get extended error information, callGetLastError().  If the buffer is not large enough to hold the complete list, the error code isERROR_MORE_DATA and thelpcchReturnLength parameter receives the required buffer size.

The header file

<windows.h>

 

Table 13:  GetVolumePathNamesForVolumeName() information.

 

--------------------------------------------------Summary------------------------------------------------------

 

Windows Volume Management Functions

 

The following Tables are the lists of the functions for volume management and control codes, structures and enumerations used for file management.  If you think you already familiar and knew how to program using those APIs, then I pass the baton to you!

 

The following functions are used in volume management.

 

Function

Description

DefineDosDevice()

Defines, redefines, or deletes MS-DOS device names.

GetDriveType()

Determines whether a disk drive is a removable, fixed, CD-ROM, RAM disk, or network drive.

GetLogicalDrives()

Returns a bitmask representing the currently available disk drives.

GetLogicalDriveStrings()

Fills a buffer with strings that specify valid drives in the system.

GetVolumeInformation()

Retrieves information about a file system and volume.

QueryDosDevice()

Retrieves information about MS-DOS device names.

SetVolumeLabel()

Sets the label of a file system volume.

 

The following functions are used with volume mount points.

 

Function

Description

DeleteVolumeMountPoint()

Unmounts the volume from the specified volume mount point.

FindFirstVolume()

Returns the name of a volume on a computer.

FindFirstVolumeMountPoint()

Returns the name of a volume mount point on the specified volume.

FindNextVolume()

Continues a volume search started by a call to FindFirstVolume().

FindNextVolumeMountPoint()

Continues a volume mount point search started by a call to FindFirstVolumeMountPoint().

FindVolumeClose()

Closes the specified volume search handle.

FindVolumeMountPointClose()

Closes the specified mount-point search handle.

GetVolumeNameForVolumeMountPoint()

Takes a volume mount point or root directory and returns the corresponding unique volume name.

GetVolumePathName()

Retrieves the volume mount point at which the specified path is mounted.

GetVolumePathNamesForVolumeName()

Retrieves a list of path names for the specified volume name.

SetVolumeMountPoint()

Mounts the specified volume at the specified volume mount point.

 

Windows File Management

 

Windows File Management Functions

 

The following functions are used in file management.

 

Function

Description

AreFileApisANSI()

Determines whether the file I/O functions are using the ANSI or OEM character set code page.

CheckNameLegalDOS8Dot3()

Determines whether the specified name can be used to create a file on the FAT file system.

CloseHandle()

Closes an open object handle.

CopyFile()

Copies an existing file to a new file.

CopyFileEx()

Copies an existing file to a new file.

CopyProgressRoutine()

An application-defined callback function used with CopyFileEx() and MoveFileWithProgress().

CreateFile()

Creates or opens a file system object.

CreateHardLink()

Establishes an NTFS hard link between an existing file and a new file.

DeleteFile()

Deletes an existing file.

FindClose()

Closes the specified search handle.

FindFirstFile()

Searches a directory for a file whose name matches the specified file name.

FindFirstFileEx()

Searches a directory for a file whose name and attributes match those specified.

FindFirstStreamW()

Enumerates the first stream in the specified file.

FindNextFile()

Continues a file search.

FindNextStreamW()

Continues a stream search.

GetBinaryType()

Determines whether a file is executable.

GetCompressedFileSize()

Retrieves the actual number of bytes of disk storage used to store a specified file.

GetFileAttributes()

Retrieves attributes for a specified file or directory.

GetFileAttributesEx()

Retrieves attributes for a specified file or directory.

GetFileInformationByHandle()

Retrieves file information for a specified file.

GetFileSize()

Retrieves the size of a specified file.

GetFileSizeEx()

Retrieves the size of a specified file.

GetFileTime()

Retrieves the date and time that a file was created, last accessed, and last modified.

GetFileType()

Retrieves the file type of the specified file.

GetFullPathName()

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

GetLongPathName()

Converts the specified path to its long form.

GetShortPathName()

Retrieves the short path form of a specified input path.

GetTempFileName()

Creates a name for a temporary file.

GetTempPath()

Retrieves the path of the directory designated for temporary files.

MoveFile()

Moves an existing file or a directory.

MoveFileEx()

Moves an existing file or a directory.

MoveFileWithProgress()

Moves a file or directory.

ReOpenFile()

Reopens the specified file system object with different access rights, sharing mode, and flags.

ReplaceFile()

Replaces one file with another file.

SearchPath()

Searches for the specified file.

SetFileApisToANSI()

Causes the file I/O functions to use the ANSI character set code page.

SetFileApisToOEM()

Causes the file I/O functions to use the OEM character set code page.

SetFileAttributes()

Sets a file's attributes.

SetFileSecurity()

Sets the security of a file or directory object.

SetFileShortName()

Sets the short name for the specified file.

SetFileTime()

Sets the date and time that a file was created, last accessed, or last modified.

SetFileValidData()

Sets the valid data length of the specified file.

 

The following functions are used with file I/O.

 

Function

Description

CancelIo()

Cancels all pending I/O operations that were issued by the calling thread for the specified file handle.

CreateIoCompletionPort()

Associates an I/O completion port with one or more file handles.

FileIOCompletionRoutine()

An application-defined callback function used with ReadFileEx() and WriteFileEx().

FlushFileBuffers()

Clears the buffers for the specified file and causes all buffered data to be written to the file.

GetQueuedCompletionStatus()

Attempts to de-queue an I/O completion packet from a specified I/O completion port.

LockFile()

Locks a region in an open file.

LockFileEx()

Locks a region in an open file for shared or exclusive access.

PostQueuedCompletionStatus()

Posts an I/O completion packet to an I/O completion port.

ReadFile()

Reads data from a file, starting at the specified position.

ReadFileEx()

Reads data from a file asynchronously.

ReadFileScatter()

Reads data from a file and stores the data into a set of buffers.

SetEndOfFile()

Moves the end-of-file position for the specified file.

SetFilePointer()

Moves the file pointer of an open file.

SetFilePointerEx()

Moves the file pointer of an open file.

UnlockFile()

Unlocks a previously locked region in an open file.

UnlockFileEx()

Unlocks a previously locked region in an open file.

WriteFile()

Writes data to a file.

WriteFileEx()

Writes data to a file asynchronously.

WriteFileGather()

Gathers data from a set of buffers and writes the data to a file.

 

The following functions are used with file mapping.

 

Function

Description

CreateFileMapping()

Creates or opens a named or unnamed file mapping object for the specified file.

FlushViewOfFile()

Writes to the disk a byte range within a mapped view of a file.

MapViewOfFile()

Maps a view of a file into the address space of the calling process.

MapViewOfFileEx()

Maps a view of a file into the address space of the calling process.

OpenFileMapping()

Opens a named file mapping object.

UnmapViewOfFile()

Unmaps a mapped view of a file from the calling process's address space.

 

The following functions are used with the encrypted file system.

 

Function

Description

AddUsersToEncryptedFile()

Adds user keys to a specified encrypted file.

DecryptFile()

Decrypts an encrypted file or directory.

DuplicateEncryptionInfoFile()

Copies the EFS metadata from one file or directory to another.

EncryptFile()

Encrypts a file or directory.

EncryptionDisable()

Disables or enables encryption of the indicated directory and the files in it.

FileEncryptionStatus()

Retrieves the encryption status of the specified file.

FreeEncryptionCertificateHashList()

Frees a certificate hash list.

QueryRecoveryAgentsOnEncryptedFile()

Retrieves a list of recovery agents for the specified file.

QueryUsersOnEncryptedFile()

Retrieves a list of users for the specified file.

RemoveUsersFromEncryptedFile()

Removes specified certificate hashes from a specified file.

SetUserFileEncryptionKey()

Sets the user's current key to the specified certificate.

 

The following functions are used to decompress files that were compressed by the compressed by the Lempel-Ziv algorithm.

 

Function

Description

GetExpandedName()

Retrieves the original name of a compressed file.

LZClose()

Closes a file that was opened by usingLZOpenFile.

LZCopy()

Copies a source file to a destination file.

LZInit()

Allocates memory for the internal data structures required to decompress files, and then creates and initializes them.

LZOpenFile()

Creates, opens, reopens, or deletes the specified file.

LZRead()

Reads (at most) the specified number of bytes from a file and copies them into a buffer.

LZSeek()

Moves a file pointer a number of bytes from a starting position.

 

Windows File Management Control Codes

 

The following control codes are used in file management.

 

Control code

Operation

FSCTL_ALLOW_EXTENDED_DASD_IO

Signals the file system driver not to perform any I/O boundary checks on partition read or write calls. Instead, boundary checks are performed by the device driver.

FSCTL_FIND_FILES_BY_SID

Searches a directory for a file whose creator owner matches the specified SID.

FSCTL_GET_NTFS_FILE_RECORD

Retrieves the complete NTFS file record identified by the specified file identifier.

FSCTL_RECALL_FILE

Recalls a file from storage media managed by Remote Storage, the hierarchical storage management software.

 

The following control codes are used with file compression and decompression.

 

Value

Meaning

FSCTL_GET_COMPRESSION

Obtains the compression state of a file or directory

FSCTL_SET_COMPRESSION

Sets the compression state of a file or directory.

 

The following control codes are used with sparse files.

 

Value

Meaning

FSCTL_QUERY_ALLOCATED_RANGES

Scans a file for ranges of the file for which disk space is allocated.

FSCTL_SET_SPARSE

Marks a file as a sparse file.

FSCTL_SET_ZERO_DATA

Sets a range of files bytes to zeroes.

 

Windows File Management Structures

 

The following structures are used in file management.

  1. BY_HANDLE_FILE_INFORMATION

  2. EFS_CERTIFICATE_BLOB

  3. EFS_HASH_BLOB

  4. ENCRYPTION_CERTIFICATE

  5. ENCRYPTION_CERTIFICATE_HASH

  6. ENCRYPTION_CERTIFICATE_HASH_LIST

  7. ENCRYPTION_CERTIFICATE_LIST

  8. FILE_ALLOCATED_RANGE_BUFFER

  9. FILE_ZERO_DATA_INFORMATION

  10. FIND_BY_SID_DATA

  11. FIND_BY_SID_OUTPUT

  12. NTFS_FILE_RECORD_INPUT_BUFFER

  13. NTFS_FILE_RECORD_OUTPUT_BUFFER

  14. OFSTRUCT

  15. WIN32_FILE_ATTRIBUTE_DATA

  16. WIN32_FIND_DATA

  17. WIN32_FIND_STREAM_DATA

 

Windows File Management Enumeration Types

 

The following enumeration types are used in file management.

  1. FINDEX_INFO_LEVELS

  2. FINDEX_SEARCH_OPS

  3. STREAM_INFO_LEVELS

 

 

 

 

 

Further reading and digging:

 

  1. Notation used in MSDN is Hungarian Notation instead of CamelCase and is discussedVC++ programming notations.

  2. Windows data type information is inData types used in Windows programming.

  3. For Multi-bytes, Unicode characters and Localization please refer to Locale, wide characters & Unicode (Story) and Windows users & groups programming tutorials (Implementation).

  4. Structure, enum, union and typedef story can be foundC/C++ struct, enum, union & typedef.

  5. Check the best selling C, C++ and Windows books at Amazon.com.

  6. Microsoft Visual C++, online MSDN.

  7. ReactOS - Windows binary compatible OS - C/C++ source code repository, Doxygen.

 

 

 

 

 

 

|< C & Win32 programming 7 | Main | ANSI, Multi-byte, Unicode and Localization 1 >|Site Index |Download |


C & C++ Programming Tutorial |C Programming Practice