Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
SQL Server

Synchronous Writing and Reading to files using win32 system services.

Author: DevASP
Download Source Code :

In this article we will examine file seeking, reading, and writing in some detail, and look at the CreateFile function more carefully. The operations here are all synchronous,

So they block until complete no other thread can access that file for reading and writing.In the listing below contains a program that performs a simple file read, designed for a text file or a file of bytes, demonstrates a file-write operation that writes structures to a new file.



typedef struct


            char a, b, c;

      } data;


      HANDLE fileHandle;

      BOOL success;

      DWORD numWrite;

      char filename[]="data.txt";

      int x;

      data dataRec;


      // Open the file

      fileHandle = CreateFile(filename, GENERIC_WRITE,

            0, 0, CREATE_NEW, 0, 0);

      if (fileHandle == INVALID_HANDLE_VALUE)


            MessageBox("Cant create or open file");




      // write 10 structures to the file

      x = 0;



            dataRec.a ='a';

            dataRec.b ='b';

            dataRec.c = 'c';

            success = WriteFile(fileHandle, &dataRec,

                  sizeof(data), &numWrite, 0);


      while ((x++ < 10) && success);


      // Close the file



The WriteFile function is similar to the ReadFile function, writing the specified number of bytes to disk. The function does not care what the bytes represent, so you can use it to write text or structures. The program writes one structure's set of bytes in a single operation, and repeats the operation ten times.



BOOL WriteFile(HANDLE fileHandle,CONST VOID *buffer,DWORD bytesToWrite,

  LPDWORD bytesWritten,LPOVERLAPPED overlapped);



fileHandle                       Handle to a file created by CreateFile

buffer                             Data to write

bytesToWrite                 The number of bytes to write

bytesWritten                  The number of bytes actually written

overlapped                     Overlapped structure


Returns TRUE on success.


The GENERIC_WRITE constant signals that we need write access to the file, and the CREATE_NEW  constant indicates that the system should create a new file rather than overwrite an existing one  (if the file name already exists, the function fails). However, CreateFile has many other capabilities.We see CreateFile in some more detail, So lets go…



HANDLE CreateFile(LPCTSTR name,DWORD accessMode,DWORD shareMode,

   LPSECURITY_ATTRIBUTES securityAttributes,DWORD create,

   DWORD attributes,HANDLE templateFile);


Name                            Name of the file to open

AccessMode                 Read/Write mode

ShareMode                    The way the file should be shared

securityAttributes           Address of a security structure.

Create                           The way the file should be created

Attributes                      Settings for normal file attribute bits

templateFile                  File containing extended attributes


Returns a handle to the file or INVALID_HANDLE_VALUE on failure.

When using the CreateFile function, you have control over several different things:


1.      The read and write mode

2.      The way the file will be shared

3.      A variety of attributes and performance hints


You can also send the function security attributes.The second parameter passed to CreateFile controls read and write access. You can pass in any of the following three combinations:


GENERIC_READ                                   Read only

GENERIC_WRITE                                  Write only



Generally you use the third option when you plan to open a file of structures that you will read and modify simultaneously. You use GENERIC_READ when you want read-only access, and GENERIC_WRITE when you need write-only access.The third parameter passed to CreateFile controls the share mode of the file. You control access to the entire file using this parameter. The following four variations are possible:


FILE_SHARE_READ                                                            read-share from the file

FILE_SHARE_WRITE                                                           write-share the file

FILE_SHARE_READ | FILE_SHARE_WRITE                          open access

                     0                                                                    exclusive use of the file

If you pass 0 to the shareMode parameter, then the entire file is locked while you have it open. Any other process attempting to open the file will receive a share violation. The remaining options grant increasing levels of access to other processes.The create parameter controls the failure behavior of CreateFile during creation. Any of the following options is possible:


CREATE_NEW                         Create a new file. Fails if file name exists

CREATE_ALWAYS                   Create a new file. Destroys any existing file

OPEN_EXISTING                       Opens an existing file. Fails if file not found

OPEN_ALWAYS                       Creates a file if one does not exist, or opens the existing file

TRUNCATE_EXISTING               Deletes the contents of the file if it exists. Fails if it does not exist


The attributes parameter lets you set the file attributes, and it also lets you tell the system your intended use of the file so that you can improve overall system performance. You can OR together non-conflicting combinations of the following constants as needed in an application:


FILE_ATTRIBUTE_ARCHIVE                     Mark file for backup

FILE_ATTRIBUTE_NORMAL                     Default

FILE_ATTRIBUTE_HIDDEN                       Mark file as hidden

FILE_ATTRIBUTE_READONLY                 Mark file as read only

FILE_ATTRIBUTE_SYSTEM                     Mark file for OS use only

FILE_ATTRIBUTE_TEMPORARY              Mark file as temporary

FILE_FLAG_DELETE_ON_CLOSE           Delete file when closed

FILE_FLAG_SEQUENTIAL_SCAN            File will be accessed sequentially

FILE_FLAG_BACKUP_SEMANTICS         Create as backup file


If you are creating a temporary file that you want to delete when you close it, you can let the OS do it automatically using the FILE_FLAG_DELETE_ON_CLOSE and FILE_ATTRIBUTE_TEMPORARY flags. You can set file attributes at creation or change them later.

Article Comments
this article shows me that u want...
Plz write another for Asyn File reading and writing

Posted on 9/3/2006 2:53:31 PM by umair

wow good ,U r the best ,For the first time i have learnt how to use Windows API's in a simple manners.

Posted on 10/10/2006 3:44:55 AM by jinn

Add Article Comment:
Name :
Email Address :
Comments :
<< Creating Temporary Files Using Win32 System Services

Disclaimer - Privacy
© 2002-2017