My Training Period: xx hours. Before you begin, read someinstruction here. The pre-requirement for this Module arestructure,function,pointer andarray.
Using handles and Basic File Management
Creating, Deleting, and Maintaining Files
Naming a File
Naming Conventions
|
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, andLPT9. 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.
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.
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.
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 bylpszLongPath. cchBuffer - [in] Size of the buffer pointed to bylpszShortPath, in TCHARs. |
The return value | If the function succeeds, the return value is the length, inTCHARs, of the string copied tolpszShortPath, not including the terminating null character. If thelpszShortPath buffer is too small to contain the path, the return value is the size of the buffer, inTCHARs, required to hold the path. Therefore, if the return value is greater thancchBuffer, 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, callGetLastError(). |
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;
}
A sample 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, inTCHARs. 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 tolpBuffer, not including the terminating null character, inTCHARs. If thelpBuffer 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, inTCHARs. Therefore, if the return value is greater thannBufferLength, 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, callGetLastError(). |
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.
|
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.
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.
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(L"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;
}
A sample output:
C:\testfile.txt opened successfully.
C:\testfile.txt file closed successfully.
Press any key to continue
The following is a sample code run using VC++ EE 2005 on WinXp Pro.
// 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(L"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;
}
A sample output:
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;
}
A sample output:
C:\testfile.txt file created successfully, error if any, 0.
Press any key to continue
The following is a sample code run using VC++ EE 2005 on WinXp Pro.
// 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((LPCWSTR)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;
}
A sample output:
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 withFILE_ATTRIBUTE_ARCHIVE, but does not set the security descriptor specified by theSECURITY_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 ifdwCreationDisposition were CREATE_NEW. |
OPEN_EXISTING | Opens the file. The function fails if the file does not exist. You should useOPEN_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 byCreateFile(). WhenCreateFile() 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 theSE_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 theFILE_SHARE_DELETE share mode. Subsequent open requests for the file will fail, unless they specify theFILE_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 withFILE_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 theFlushFileBuffers() function. An application must meet certain requirements when working with files opened withFILE_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 useVirtualAlloc() 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 theGetDiskFreeSpace() 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 theCREATE_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 theOVERLAPPED structure is set to the signaled state. Operations that take a significant amount of time to process returnERROR_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 theOVERLAPPED 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 anOVERLAPPED 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. IfFILE_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. IfFILE_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, thedwFlagsAndAttributes 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.
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() isCREATE_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, callGetLastError().
Use the CloseHandle() function to close an object handle returned byCreateFile().
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.
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 toDeleteFile(), 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.
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.
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 theDeviceIoControl() 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, thelpFileName 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 withCreateFile().
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.
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 drive0.
To open tape drive 0 in an application written in C or C++, use the file name "\\\\.\\TAPE0".
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.
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 theCONIN$ value to specify console input and theCONOUT$ value to specify console output. CONIN$ gets a handle to the console's input buffer, even if theSetStdHandle() function redirected the standard input handle. To get the standard input handle, use theGetStdHandle() function. CONOUT$ gets a handle to the active screen buffer, even ifSetStdHandle() redirected the standard output handle. To get the standard output handle, useGetStdHandle(). |
dwDesiredAccess | GENERIC_READ | GENERIC_WRITE is preferred, but either one can limit access. |
dwShareMode | When openingCONIN$, be sure to specifyFILE_SHARE_READ. When opening CONOUT$, be sure to specifyFILE_SHARE_WRITE. If the calling process inherited the console or if a child process should be able to access the console, this parameter must beFILE_SHARE_READ | FILE_SHARE_WRITE. |
lpSecurityAttributes | If you want the console to be inherited, thebInheritHandle() member of the SECURITY_ATTRIBUTES structure must be TRUE. |
dwCreationDisposition | You should specifyOPEN_EXISTING when using CreateFile() to open the console. |
dwFlagsAndAttributes | Ignored. |
hTemplateFile | Ignored. |
Table 22: CreateFile() parameters for console handles. |
The following list shows the effects of various settings of dwDesiredAccess andlpFileName.
lpFileName | dwDesiredAccess | Result |
CON | GENERIC_READ | Opens console for input. |
CON | GENERIC_WRITE | Opens console for output. |
CON | GENERIC_READGENERIC_WRITE | CausesCreateFile() to fail; GetLastError() returns ERROR_FILE_NOT_FOUND. |
Table 23: Effect of thedwDesiredAccess and lpFileName parameters. |
To use operating system resources efficiently, an application should close files when they are no longer needed by using theCloseHandle() function.
If a file is open when an application terminates, the system closes it automatically. The following code closes the file, whose handle is stored in the hFile variable.
CloseHandle(hFile);
It just close a file, not delete the file from disk.
The DeleteFile() function can be used to delete a file. The file must, however, be closed before any attempt to delete it will succeed.
The following code closes and deletes the file named testfile.txt, whose handle is stored in the hFile variable.
CloseHandle(hFile);
DeleteFile("testfile.txt");
If you are deleting an open file or directory on a remote machine and it has already been opened on the remote machine without the read share permission set, do not call CreateFile() or OpenFile() to open the file or directory for deletion first. Doing so will result in a sharing violation.
The following example uses hFile as a handle and then CreateFile() to open a new file for writing. At the end the handle is closed usingCloseHandle() and the file is deleted using DeleteFile().
The following example uses CreateFile() function to create a file named testfile.txt located in drive C: (root) that will be opened for writing, shared for writing, create the file if it is does not exist, using default access security, with normal, archive and impersonate security and no template.
#include <windows.h>
#include <stdio.h>
int main()
{
// handle to a file
HANDLE hFile;
// file and path, change accordingly
char fname[30] = "c:\\testfile.txt";
hFile = CreateFile(fname, // file to be opened
GENERIC_WRITE, // open for writing
FILE_SHARE_WRITE, // share for writing
NULL, // default security
CREATE_ALWAYS, // create new file only
FILE_ATTRIBUTE_NORMAL |FILE_ATTRIBUTE_ARCHIVE | SECURITY_IMPERSONATION,
// normal file archive and impersonate client
NULL); // no attribute template
if(hFile == INVALID_HANDLE_VALUE)
printf("Could not open %s file, error %d\n", fname, GetLastError());
else
{
printf("File's HANDLE is OK!\n");
printf("%s opened successfully!\n", fname);
}
if(CloseHandle(hFile) != 0)
printf("CloseHandle() succeeded!\n");
if(DeleteFile(fname) != 0)
printf("%s file successfully deleted!\n", fname);
return 0;
}
A sample output:
File's HANDLE is OK!
c:\testfile.txt opened successfully!
CloseHandle() succeeded!
c:\testfile.txt file successfully deleted!
Press any key to continue
In this example the handle is closed, if not, a subsequent call to open this file with CreateFile() will fail until the handle is closed.
The following is a sample run on VC++ EE with SDK run on Win XP Pro SP2.
#include <windows.h>
#include <stdio.h>
int main()
{
// handle to a file
HANDLE hFile;
// file and path, change accordingly
char fname[30] = "C:\\Documents and Settings\\Mikerisan\\Desktop\\doc1.doc";
hFile = CreateFile((LPCWSTR)fname, // file to be opened
GENERIC_WRITE, // open for writing
FILE_SHARE_WRITE, // share for writing
NULL, // default security
CREATE_ALWAYS, // create new file only
FILE_ATTRIBUTE_NORMAL |FILE_ATTRIBUTE_ARCHIVE | SECURITY_IMPERSONATION,
// normal file archive and impersonate client
NULL); // no attribute template
if(hFile == INVALID_HANDLE_VALUE)
printf("Could not open %s file, error %d\n", fname, GetLastError());
else
{
printf("File's HANDLE is OK!\n");
printf("%s opened successfully!\n", fname);
}
if(CloseHandle(hFile) != 0)
printf("CloseHandle() succeeded!\n");
if(DeleteFile((LPCWSTR)fname) != 0)
printf("%s file successfully deleted!\n", fname);
return 0;
}
A sample output:
Keep in mind that the file seem not deleted when we check it! Can you find the reason?