|< C & Win32 programming 4 | Main | C & Win32 programming 6 >| Site Index | Download |


 

 

 

 

MODULE E

WIN32 AND C PROGRAMMING 5

 

 

 

 

What are in this Module?

  1. Setting and Getting the Timestamp of a File

  2. How to access Structure’s element

  3. The Parameters

  4. The Return Values

  5. FILETIME Structure

  6. Members

  7. SYSTEMTIME Structure

  8. Members

  9. Testing for the End of a File

  10. Positioning a File Pointer

 

 

My Training Period: yy hours. Before you begin, read some instruction here.

 

Abilities that supposed to be acquired:

  • Be familiar and play around with the Win32 programming.

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

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

Setting and Getting the Timestamp of a File

  • Applications can retrieve and set the date and time a file was created, last modified, or last accessed by using the GetFileTime() and SetFileTime() functions.

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

Information

Description

The function

GetFileTime().

The use

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

The prototype

BOOL GetFileTime( HANDLE     hFile, LPFILETIME lpCreationTime, LPFILETIME lpLastAccessTime, LPFILETIME lpLastWriteTime );

example

HANDLE hFile1;

FILETIME ftCreate, ftAccess, ftWrite;

 

hFile1 = CreateFile(...);

GetFileTime(hFile1, &ftCreate, &ftAccess, &ftWrite);

The parameters

hFile - [in] Handle to the files for which to get dates and times.  The file handle must have been created with the GENERIC_READ access right.

lpCreationTime - [out] Pointer to a FILETIME structure to receive the date and time the file was created.  This parameter can be NULL if the application does not require this information.

lpLastAccessTime - [out] Pointer to a FILETIME structure to receive the date and time the file was last accessed.  The last access time includes the last time the file was written to, read from, or, in the case of executable files, run.  This parameter can be NULL if the application does not require this information.

lpLastWriteTime - [out] Pointer to a FILETIME structure to receive the date and time the file was last written to.  This parameter can be NULL if the application does not require this information.

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, call GetLastError().

The header file

<windows.h>

 

Table 1:  GetFileTime() information.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

#include <windows.h>

#include <stdio.h>

 

int main()

{

// a file handle

HANDLE hFile1;

FILETIME ftCreate, ftAccess, ftWrite;

SYSTEMTIME stUTC, stLocal, stUTC1, stLocal1, stUTC2, stLocal2;

 

// a filename, change accordingly

char fname1[ ] = "c:\\testfile.txt";

// temporary storage for file sizes

DWORD dwFileSize;

DWORD dwFileType;

 

// opening the existing file

hFile1 = CreateFile(fname1,                // 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

 

if(hFile1 == INVALID_HANDLE_VALUE)

{

    printf("Could not open %s file, error %d\n", fname1, GetLastError());

    return 4;

}

dwFileType = GetFileType(hFile1);

dwFileSize = GetFileSize(hFile1, NULL);

printf("%s size is %d bytes and file type is %d\n", fname1, dwFileSize, dwFileType);

 // retrieve the file times for the file.

 if(!GetFileTime(hFile1, &ftCreate, &ftAccess, &ftWrite))

{

  printf("Something wrong lol!\n");

         return FALSE;

}

 // convert the created time to local time.

 FileTimeToSystemTime(&ftCreate, &stUTC);

 SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);

// convert the last-access time to local time.

FileTimeToSystemTime(&ftAccess, &stUTC1);

SystemTimeToTzSpecificLocalTime(NULL, &stUTC1, &stLocal1);

// convert the last-write time to local time.

FileTimeToSystemTime(&ftWrite, &stUTC2);

SystemTimeToTzSpecificLocalTime(NULL, &stUTC2, &stLocal2);

// build a string showing the date and time.

printf("Created on: %02d/%02d/%d %02d:%02d\n", stLocal.wDay, stLocal.wMonth, stLocal.wYear, stLocal.wHour, stLocal.wMinute);

printf("Last accessed: %02d/%02d/%d %02d:%02d\n", stLocal1.wDay, stLocal1.wMonth, stLocal1.wYear, stLocal1.wHour, stLocal1.wMinute);

printf("Last written: %02d/%02d/%d %02d:%02d\n", stLocal2.wDay, stLocal2.wMonth, stLocal2.wYear, stLocal2.wHour, stLocal2.wMinute);

// close the file's handle and itself

CloseHandle(hFile1);

return 0;

}

 

The output:

 

c:\testfile.txt size is 1289 bytes and file type is 1

Created on: 24/05/2005  22:33

Last accessed: 24/05/2005  22:40

Last written: 24/05/2005  22:37

Press any key to continue

 

---------------------------------------------Have a break------------------------------------------------

 

How to access Structure’s element

BOOL FileTimeToSystemTime( const FILETIME*     lpFileTime,  LPSYSTEMTIME    lpSystemTime);

The Parameters

 

Parameter

Description

lpFileTime

[in] Pointer to a FILETIME structure containing the file time to convert to system date and time format. This value must be less than 0x8000000000000000.  Otherwise, the function fails.

lpSystemTime

[out] Pointer to a SYSTEMTIME structure to receive the converted file time.

 

Table 2:  FileTimeToSystemTime() parameters.

 

The Return Values

FILETIME Structure

typedef struct _FILETIME {
	DWORD dwLowDateTime;
	DWORD dwHighDateTime;
} FILETIME, 
 
*PFILETIME;

Members

 

Member

Description

dwLowDateTime

Low-order part of the file time.

dwHighDateTime

High-order part of the file time.

 

Table 3:  _FILETIME structure member.

 

SYSTEMTIME Structure

typedef struct _SYSTEMTIME {
	WORD wYear;
	WORD wMonth;
	WORD wDayOfWeek;
	WORD wDay;
	WORD wHour;
	WORD wMinute;
	WORD wSecond;
	WORD wMilliseconds;
} SYSTEMTIME, *PSYSTEMTIME;

Members

 

Member

Description

wYear

The year. This value must be greater than 1601. For Windows Server 2003, Windows XP, this value cannot be greater than 30827.

wMonth

The month; January = 1, February = 2, and so on.

wDayOfWeek

The day of the week; Sunday = 0, Monday = 1, and so on.

wDay

The day of the month.

wHour

The hour.

wMinute

The minute.

wSecond

The second.

wMilliseconds

The millisecond.

 

Table 4:  _SYSTEMTIME structure members.

#include <windows.h>

#include <stdio.h>

 

int main()

{

// a file handle

HANDLE hFile1;

// FILETIME is another name for struct _FILETIME structure (a typedef)

FILETIME ftCreate;

// SYSTEMTIME is another name for struct _SYSTEMTIME structure (a typedef)

SYSTEMTIME stUTC, stLocal;

 

//filename

char fname1[ ] = "c:\\testfile.txt";

// opening the existing file

hFile1 = CreateFile(fname1,                      // 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

 

if(hFile1 == INVALID_HANDLE_VALUE)

{

    printf("Could not open %s file, error %ul\n", fname1, GetLastError());

    return 4;

}

 

// retrieve created file times for the file.

if(!GetFileTime(hFile1, &ftCreate, NULL, NULL))

{

   printf("Something wrong!\n");

    return FALSE;

}

 // viewing the unreadable...

// filing the 32 bit low part into variable low and another 32 bit high part into variable high

//Accessing the FILETIME structures' members, assigning them to some variables...

DWORD low = ftCreate.dwLowDateTime;

DWORD high = ftCreate.dwHighDateTime;

// trying to display the content in hex...

printf("Unreadable format...\n");

printf("32 bit low part = %0X and high = %0X\n", low, high);

// convert the file created time to local time.

 FileTimeToSystemTime(&ftCreate, &stUTC);

 SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);

printf("\nReadable format...\n");

// build a readable string showing the date and time. Accessing the SYSTEMTIME structure's member

printf("UTC System Time\n");

printf("Created on: %02d/%02d/%d %02d:%02d\n", stUTC.wDay, stUTC.wMonth, stUTC.wYear, stUTC.wHour, stUTC.wMinute);

// accessing the SYSTEMTIME structures' members

printf("Local time\n");

printf("Created on: %02d/%02d/%d %02d:%02d\n", stLocal.wDay, stLocal.wMonth, stLocal.wYear, stLocal.wHour, stLocal.wMinute);

// close the file's handle and itself

CloseHandle(hFile1);

return 0;

}

 

The output:

 

Unreadable format...

32 bit low part = 97AFA6A0 and high = 1C5606D

 

Readable format...

UTC System Time

Created on: 24/05/2005 14:33

Local time

Created on: 24/05/2005 22:33

Press any key to continue

 

----------------------------------End on using structure in Win32 programming-----------------------------

 

Testing for the End of a File

// attempt a synchronous read operation
bResult = ReadFile(hFile, &inBuffer, nBytesToRead, &nBytesRead, NULL);

	
// check for eof
if(bResult &&  nBytesRead == 0) 
{
    // at the end of the file
}
  1. ReadFile() returns FALSE and GetLastError() returns ERROR_HANDLE_EOF.

  2. ReadFile() returns FALSE and GetLastError() returns ERROR_IO_PENDING.

  3. GetOverlappedResult() returns FALSE and GetLastError() returns ERROR_HANDLE_EOF.

// attempt to initiate an asynchronous read operation.
bResult = ReadFile(hFile, &inBuffer, nBytesToRead, &nBytesRead, NULL);
 
// check if there was a problem.
if(!bResult) 
{
    switch(dwError = GetLastError())
    {
        case ERROR_HANDLE_EOF:
        // at the end of the file.
            break;
        case ERROR_IO_PENDING:
        // I/O pending.
           break;
    }
}
 
// check on an asynchronous read operation.
bResult = GetOverlappedResult(hFile, &gOverlapped, &nBytesRead, TRUE);
 
// check if there was a problem.
if(!bResult) 
{
    switch(dwError = GetLastError())
    {
        case ERROR_HANDLE_EOF:
        // at the end of the file
    }
}

Positioning a File Pointer

 

Information

Description

The function

SetFilePointer().

The use

Moves the file pointer of an open file.

The prototype

DWORD SetFilePointer( HANDLE hFile, LONG   lDistanceToMove, PLONG  lpDistanceToMoveHigh, DWORD  dwMoveMethod);

Example

HANDLE hFile;

 

hFile = CreateFile(...);

SetFilePointer(

    hFile, // must have GENERIC_READ and/or GENERIC_WRITE

    0,     // do not move pointer

    NULL,  // hFile is not large enough to need this pointer

    FILE_CURRENT);  // provides offset from current position

The parameters

hFile - [in] Handle to the file whose file pointer is to be moved.  The file handle must have been created with the GENERIC_READ or GENERIC_WRITE access right.

lDistanceToMove - [in] Low-order 32 bits of a signed value that specifies the number of bytes to move the file pointer.  If lpDistanceToMoveHigh is not NULL, lpDistanceToMoveHigh and lDistanceToMove form a single 64-bit signed value that specifies the distance to move.  If lpDistanceToMoveHigh is NULL, lDistanceToMove is a 32-bit signed value.  A positive value for lDistanceToMove moves the file pointer forward in the file, and a negative value moves the file pointer backward.

lpDistanceToMoveHigh - [in] Pointer to the high-order 32 bits of the signed 64-bit distance to move.  If you do not need the high-order 32 bits, this pointer must be set to NULL.  When non-NULL, this parameter also receives the high-order DWORD of the new value of the file pointer.

dwMoveMethod - [in] Starting point for the file pointer move.  This parameter can be one of the following values:

  1. FILE_BEGIN - The starting point is zero or the beginning of the file.

  2. FILE_CURRENT - The starting point is the current value of the file pointer.

  3. FILE_END - The starting point is the current end-of-file position.

The return value

If the SetFilePointer() function succeeds and lpDistanceToMoveHigh is NULL, the return value is the low-order DWORD of the new file pointer.  If lpDistanceToMoveHigh is not NULL, the function returns the low order DWORD of the new file pointer, and puts the high-order DWORD of the new file pointer into the LONG pointed to by that parameter. If the function fails and lpDistanceToMoveHigh is NULL, the return value is INVALID_SET_FILE_POINTER.  To get extended error information, call GetLastError(). If the function fails, and lpDistanceToMoveHigh is non-NULL, the return value is INVALID_SET_FILE_POINTER. However, because INVALID_SET_FILE_POINTER is a valid value for the low-order DWORD of the new file pointer, you must check GetLastError() to determine whether an error occurred.  If an error occurred, GetLastError() returns a value other than NO_ERROR. If the new file pointer would have been a negative value, the function fails, the file pointer is not moved, and the code returned by GetLastError() is ERROR_NEGATIVE_SEEK.

The header file

<windows.h>

 

Table 5:  SetFilePointer() information.

#include <windows.h>

#include <stdio.h>

 

int main()

{

// handle for file

HANDLE hFile;

DWORD dwCurrentFilePosition;

 

// file and path, change accordingly to other file available on your machine for testing

char fname[20] = "c:\\module15.txt";

 

hFile = CreateFile(fname,                                // file to be opened

                GENERIC_WRITE,                           // open for writing

                FILE_SHARE_READ,                     // share for reading

                NULL,                                                // default security

                OPEN_EXISTING,                           // open existing file

                FILE_ATTRIBUTE_READONLY,  // the file is read only

                NULL);                                               // no attribute template

 

if(hFile == INVALID_HANDLE_VALUE)

    printf("Could not open %s file, error %d\n", fname, GetLastError());

printf("File's HANDLE is OK!\n");

dwCurrentFilePosition = SetFilePointer(

    hFile,  // must have GENERIC_READ and/or GENERIC_WRITE

    0,        // do not move pointer

    NULL,  // hFile is not large enough to need this pointer

    FILE_CURRENT);  //provides offset from current position

 

printf("Current file pointer position: %d\n", dwCurrentFilePosition);

dwCurrentFilePosition = SetFilePointer(

    hFile, // must have GENERIC_READ and/or GENERIC_WRITE

    10,    // 10 bytes

    NULL,  // hFile is not large enough to need this pointer

    FILE_CURRENT);  // provides offset from current position

printf("Current file pointer position: %d\n", dwCurrentFilePosition);

return 0;

}

 

The output:

 

File's HANDLE is OK!

Current file pointer position: 0

Current file pointer position: 10

Press any key to continue

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Further reading and digging:

 

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

  2. Microsoft Visual C++, online MSDN.

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

  4. Windows data type information is in Data types used in Windows programming.

  5. Structure, enum, union and typedef story can be found C/C++ struct, enum, union & typedef.

  6. Notation used in MSDN is Hungarian Notation instead of CamelCase and is discussed VC++ programming notations.

 

 

 

 

 

|< C & Win32 programming 4 | Main | C & Win32 programming 6 >| Site Index | Download |


 

C & C++ Programming Tutorial | C Programming Practice