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


 

 

 

 

 

MODULE C1

INTRO TO WIN32 AND C PROGRAMMING 2

 

 

 

 

What are in this Module?

  1. Using handles and Basic File Management

  2. Creating, Deleting, and Maintaining Files

  3. Naming a File

  4. Naming Conventions

  5. Maximum Path Length

  6. Relative Paths

  7. Short and Long File Names

  8. Creating and Opening Files – Collecting the Information

  9. The prototype

  10. The Parameters

  11. The Return Values

  12. Files

  13. Directories

  14. Physical Disks and Volumes

  15. Tape Drives

  16. Communications Resources

  17. Consoles

  18. Closing Files

  19. Deleting Files

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

My Training Period: xx hours. Before you begin, read some instruction here. The pre-requirement for this Module are structure, function, pointer and array.

 

The Win32 skills that supposed to be acquired:

 

 

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:

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

  2. 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>.

  1. 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 |.

  2. 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).

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

  4. 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.

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

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

 

Maximum Path Length

\\?\D:\<path>

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

Relative Paths

Short and Long File Names

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.

#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

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.

#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;

}

 

A sample output:

 

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

Press any key to continue

Creating and Opening Files – Collecting the Information

The prototype

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

// 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

// 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:

 

// 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

// 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:

 

 

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.

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.

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

Files

Directories

Physical Disks and Volumes

  1. The caller must have administrative privileges.

  2. The dwCreationDisposition parameter must have the OPEN_EXISTING flag.

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

String

Meaning

\\.\PHYSICALDRIVE0

Opens the first physical drive.

\\.\PHYSICALDRIVE2

Opens the third physical drive.

 

Table 20.

String

Meaning

\\.\A:

Opens drive A (floppy drive).

\\.\C:

Opens drive C (volume).

 

Table 21.

Tape Drives

Communications Resources

Consoles

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.

lpSecurityAttributes

If you want the console to be inherited, the bInheritHandle() member of the SECURITY_ATTRIBUTES structure must be TRUE.

dwCreationDisposition

You should specify OPEN_EXISTING when using CreateFile() to open the console.

dwFlagsAndAttributes

Ignored.

hTemplateFile

Ignored.

 

Table 22:  CreateFile() parameters for console handles.

lpFileName

dwDesiredAccess

Result

CON

GENERIC_READ

Opens console for input.

CON

GENERIC_WRITE

Opens console for output.

CON

GENERIC_READ GENERIC_WRITE

Causes CreateFile() to fail; GetLastError() returns ERROR_FILE_NOT_FOUND.

 

Table 23:  Effect of the dwDesiredAccess and lpFileName parameters.

 

Closing Files

CloseHandle(hFile);

Deleting Files

CloseHandle(hFile); 
DeleteFile("testfile.txt");

#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

#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:

 

 

 

 

 

 

 

 

 

 

 

 

 

Further reading and digging:

 

  1. For Multibytes, Unicode characters and Localization please refer to Locale, Wide Character & Unicode (Story) and Windows Users & Groups tutorial

  2. Structure, enum, union and typedef story can be found in struct, typedef, union & enum.

  3. Notation used in MSDN is Hungarian Notation instead of CamelCase and is discussed C/C++ Notations.

  4. More for Windows File system, directory and files is Windows File System Supplementary Notes.

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

  6. Microsoft Visual C++, online MSDN.

 

 

 

 

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


 

C & C++ Programming Tutorial | C Programming Practice