顯示具有 程式設計 標籤的文章。 顯示所有文章
顯示具有 程式設計 標籤的文章。 顯示所有文章

2013年5月24日 星期五

ADOQuery的LockType屬性


  • LockType屬性含義:
  • ltUnspecified  不特別指定 
  • ltReadOnly  選出來的資料表只能讀,無法寫入 
  • ltPessimistic  選出來的資料表可以寫入,當改記錄寫入時會立刻寫入並鎖定 
  • ltOptimistic  選出來的資料表可寫入,當該記錄表寫入時不會立刻寫入但會鎖定,當執行updates時才正式寫入改記錄 
  • ltBatchOptimistic  選出來的資料表可寫入,當該記錄寫入時不會立刻寫入但會鎖定,當執行updates才正式整批寫入該記錄(可以修改多條整批update)        

2013年2月2日 星期六

ServerSocket 元件的幫助


ServerSocket 元件的幫助

ServerSocket 元件
一、屬性
TServerSocket.Socket
指定獲得描述監聽連接端點的TServerWinSocket對象.
使用socket獲得:
1、在socket服務器上的當前活動連接的信息。
2、被socket服務器緩衝使用的連接線程信息。
3、能訪問被Windows socket API需要而調用的監聽連接的Windows socket句柄。

TServerSocket.ServerType
type TServerType = (stNonBlocking, stThreadBlocking);
繼承於TCustomServerSocket,指定被socket服務器接收到的每一個連接要么是non-
blocking(非阻塞模式),要么自動分配一個獨立的執行
線程。
描述:
設定ServerType為線程阻塞模式,服務器接收每一個socket連接會自動的產生一個新的
線程。當設定為線程阻塞模式,當讀或寫的時候,連接線程的執行將會延緩至
通過連接的所有信息傳輸結束。當socket服務器需要讀寫的時候,每一個連接的線程會
觸發OnClientRead或OnClientWrite事件。
(實際使用時,設定ServerType為線程阻塞模式,OnClientRead沒有發現被觸發)
設定ServerType為非阻塞模式,異步的處理所有通過Scoket連接的讀寫。當ServerType
為非阻塞模式,所有的客戶端連接缺省的在一個執行線程中處理。
當客戶端連接的另一端通過連接發送或者接收數據時,服務器端的OnClientRead或
OnClientWrite事件觸發。
注:當ServerType設定為stThreadBlocking時, 有一點很重要,OnClient相應的事件都
應當是線程安全的。
TServerSocket.ThreadCacheSize
繼承於TCustomServerSocket,指定能被新的客戶端連接重新使用的線程最大數量。
描述:
當ServerType設定為stThreadBlocking時,每一個被Socket服務器接受的新的連接會被給
於一個獨立的執行線程。為了提高性能,服務器sockets並不是當連接關閉的時候釋放掉
這些線程,而是把這些線程存儲在緩衝區裡。新的連接能夠重新使用緩衝裡的這些線程
。而不需要socket服務器每次接受一個連接的時候便創建一個線程。
設定ThreadCacheSize來指定能被緩衝復用的線程數量。理想的線程緩衝區大小依賴於
socket服務器接收到的客戶端的請求數量和頻率。如果線程緩衝區設的太低,當客戶端
連接被接收時,服務器sockets將會花費大量的時間在創建和釋放線程上。如果線程緩衝
區大小設定過高,服務器sockets就會沒必要的鎖定沒有被復用的線程內存。
(默認大小為10)
TAbstractSocket.Active
指明和其他機器的socket連接通訊是否是打開的或者是可利用的。
描述:
試圖使用或者改變socket連接前,讀取Ative屬性來確定連接是打開的或者已就緒。
對客戶端而言,設定Active用於打開或關閉一個與其他機器的socket連接。
對服務器而言,設定Active用於打開或關閉一個對客戶端請求可以利用的監聽連接。
在設計期,設定Active為True時,當應用程序運行時,使socket打開。
在運行期,使用Open或Close方法來打開或關閉連接。
TAbstractSocket.Port
(略)
要監聽的端口,如果在Service屬性中指定了服務類型,此屬性將被忽略。
TAbstractSocket.Service
(略)
繼承於TComponent的其他屬性:
TComponent.ComObject
指定被組件執行的接口引用。
TComponent.ComponentCount
指出被組件擁有的組件數量。
TComponent.ComponentIndex
指出組件擁有的組件的在組件屬性排列中的位置。
TComponent.Components
列出被組件所擁有的所有組件。
TComponent.ComponentState
描述當前組件狀態,並指出當前狀態State;
type TComponentState = set of (csLoading, csReading, csWriting, csDestroying,
csDesigning, csAncestor, csUpdating, csFixups, csFreeNotification, csInline,
csDesignInstance);
property ComponentState: TComponentState;
TComponent.ComponentStyle
管理組件的行為。
type TComponentStyle = set of (csInheritable, csCheckPropAvil,csSubComponent,
csTransient);
property ComponentStyle: TComponentStyle;
是一個只讀屬性,各種組件類型的標記是組件定義的一部分,在組件構造器中指定。一
個例外是csSubComponent,它可以在調用SetSubComponent 方法時設定。
TComponent.DesignInfo
TComponent.Name
TComponent.Owner
TComponent.Tag
TComponent.VCLComObject
二、方法
TServerSocket.Create
創建一個TServerSocket的實例。
描述:
在運行期調用TServerSocket.Create創建和初始化一個TServerSocket組件,在設計期放
置一個TServerSocket組件,自動創建一個socket服務器。
調用繼承的構造器之後,Create方法做了以下動作:
1、為Socket服務器分配一個封裝了Windows socket連接的TServerWinSocket對象。
2、初始化了Socket服務器的事件和錯誤發包器。
3、初始化線程緩衝區大小為10。
TCustomServerSocket.Destroy
銷毀一個TCustomServerSocket實例。
描述:
不要在一個應用程序中調用destroy方法,相反,使用free,Free方法能夠檢測服務器
socket不為nil,然後自動調用destroy。
destroy方法釋放描述監聽連接服務終點的TServerWinSocket對象。
TAbstractSocket.Close
TAbstractSocket.Open
繼承於TComponent的方法
TComponent.BeforeDestruction
在第一個destructor銷毀器被調用之前執行的所有操作。
描述:
組件的第一個destructor銷毀器執行之前,BeforeDestruction會被立即自動執行,不
要在你的應用程序中明確調用。
TComponent.Destroying
指出組件和他擁有的組件將被銷毀。
描述:
Destroying方法在ComponentState屬性中將狀態設定為csDestroying 。
對每一個擁有的組件一次調用destroying方法,使它們的csDestroying標記被設定。如
果csDestroying已經設定了,Destroying將不起作用。
沒有必要直接調用Destroying方法,Destroying方法自動在destructor 銷毀器中自動執
行,以調用free方法開始,以對象本身destroying結束。
TComponent.ExecuteAction
將組件作為目標激發一個行為.
function ExecuteAction(Action: TBasicAction): Boolean; dynamic;

TComponent.FindComponent
指出組件是否擁有一個給定的組件
function FindComponent(const AName: string): TComponent; 。 。 。 。 。 。

(還有很多繼承於TComponent的方法)
三、事件
分別繼承於TCustomServerSocket和TCustomSocket
繼承於TCustomServerSocket的事件:
TCustomServerSocket.OnClientConnect
當客戶端完成一個被服務器socket接受的連接時觸發此事件。
property OnClientConnect: TSocketNotifyEvent;
描述:
當一個客戶端socket完成一個向服務器socket的連接後,寫一個OnClientConnect事件句
柄進行指定的動作。例如:socket可以在OnClientConnect事件中通過連接開始讀或寫。
以下是服務器Socket一路執行到OnClientConnect所發生的事件:
1、服務器Socket打開或監聽前,一個OnListen事件先發生。
2、服務器Socket在一個監聽隊列裡接收客戶端請求,服務器Socket接受這些請求中的一
個,並且為新的Socket連接接收一個windows socket句柄。
3、服務器socket產生一個OnGetSocket事件,在windows句柄​​中傳遞。如果為一個新的連
接TServerClientWinSocket對像沒有在OnGetSocke事件句柄中被創建,那麼服務器
socket將會創建一個。 TServerWinSocket對象繼續監聽其他客戶端。
4、使用一個新的TServerClientWinSocket對象,OnAccept三事件被觸發。
5、如果ServerType是stThreadBlocking,並且緩衝區中沒有可用的線程,OnGetThread
事件會發生,如果OnGetThread事件句柄沒有創建線程,服務器socket將會創建
TServerClientThread。
6、如果ServerType是stThreadBlocking,當線程開始執行時,OnThreadStart事件觸發
。
7、客戶端完成到TServerClientWinSocket對象的連接,OnClientConnect事件觸發
。
注意:
如果ServerType是stThreadBlocking,確保OnClientConnect事件裡的代碼是線程安全的
使用GetClientThread方法參數來訪問指定的線程信息。
注意:
當設定相關TServerWinSocket的OnClientConnect事件句柄,TServerSocket的
OnClientConnect事件句柄也被設定。
TCustomServerSocket.OnClientDisconnect
(略)
TCustomServerSocket.OnClientError
當建立、使用、或者終止一個針對單獨客戶Socket的連接發生錯誤時觸發。
描述:
寫一個OnClientError事件句柄響應針對一個獨立客戶端連接所引發的錯誤。在
OnClientError事件句柄中將ErrorCode參數設為0,能夠成功的​​​​處理錯誤狀態,防止錯誤
被觸發。
TCustomServerSocket.OnClientRead
TCustomServerSocket.OnClientWrite
TCustomServerSocket.OnGetSocket
當服務器Socket需要創建一個新的TServerClientWinSocket對象來描述一個到客戶端的
連接端點時觸發。
property OnGetSocket: TGetSocketEvent;
描述:
寫一個OnGetSocket事件句柄創建一個指定的TServerClientWinSocket類的繼承對象,供
服務器Socket使用。在參數ClientSocket中返回新的TServerClientWinSocket對象,
Sender參數是描述監聽連接服務端點的TServerWinSocket對象。
TCustomServerSocket.OnGetThread
當服務器socket為客戶端socket的連接需要創建一個新的執行線程時觸發。
property OnGetThread: TGetThreadEvent;
描述:
當客戶端連接過來的時候,OnGetThread事件句柄創建一個指定的TServerClientThread
子類,在參數SocketThread中,表示返回一個新的TServerClientThread對象。
大多數應用程序使用線程阻塞服務器組件,就是想要提供OnGetThread 事件句柄,並且
應用TServerClientThread在自己的線程安全方式下進行讀寫操作,而不是依賴缺省的在
OnClientRead事件或者OnClientWrite事件中的TServerClientThread,因為
OnClientRead事件和OnClientWrite事件句柄存在於服務器socket,而服務器socket在全
局內存中。 (我理解,也就是單線程的)
Sender參數也​​​​就是描述監聽連接端點的TServerWinSocket對象。 ClientSocket參數描述
將要與客戶端形成的服務連接端點。
TCustomServerSocket.OnThreadEnd
TCustomServerSocket.OnThreadStart
(略)
繼承於TCustomSocket的事件
TCustomSocket.OnAccept
接受客戶端的連接請求之後馬上觸發。
客戶端連接請求被接受之後,為服務器socket寫OnAccept事件句柄進行指定的操作。

2010年7月6日 星期二

簡易縮圖網頁產生器_by_AaronJiang

簡易縮圖網頁產生器:

只須指定照片目錄即可自動產生縮圖與網頁
程式畫面:


縮圖網頁截圖:
下載連結 2

軟體原創 轉貼請註明出處

2008年10月22日 星期三

程序與程序間共用記憶體(Shared Memory)

CreateFileMapping

The CreateFileMapping function creates or opens a named or unnamed file mapping object for a specified file.

HANDLE CreateFileMapping(
HANDLE hFile,
LPSECURITY_ATTRIBUTES lpAttributes,
DWORD flProtect,
DWORD dwMaximumSizeHigh,
DWORD dwMaximumSizeLow,
LPCTSTR lpName
);

Parameters

hFile
[in] A handle to the file from which to create a mapping object.

The file must be opened with access rights that are compatible with the protection flags that the flProtect parameter specifies. It is not required, but it is recommended that files you intend to map be opened for exclusive access. For more information, see File Security and Access Rights.

If hFile is INVALID_HANDLE_VALUE, the calling process must also specify a mapping object size in the dwMaximumSizeHigh and dwMaximumSizeLow parameters. In this scenario, CreateFileMapping creates a file mapping object of a specified size that the operating system paging file backs, instead of by a named file in the file system.

The file mapping object can be shared by duplication, inheritance, or by name. The initial contents of the pages in a file mapping object are 0 (zero).

lpAttributes
[in] A pointer to a SECURITY_ATTRIBUTES structure that determines whether or not a returned handle can be inherited by child processes.

If lpAttributes is NULL, the handle cannot be inherited.

The lpSecurityDescriptor member of the structure specifies a security descriptor for a new file mapping object.

If lpAttributes is NULL, the file mapping object gets a default security descriptor. The access control lists (ACL) in the default security descriptor for a file mapping object come from the primary or impersonation token of the creator. However, doing this involves potential security risks. To avoid the risks, use a valid SECURITY_ATTRIBUTES structure.

flProtect
[in] The protection for the file view, when the file is mapped.

This parameter can be one of the following values.

Value Meaning
PAGE_READONLY Gives read-only access to a specific region of pages.

An attempt to write to a specific region results in an access violation. The file that the hFile parameter specifies must be created with the GENERIC_READ access right.

PAGE_READWRITE Gives read/write access to a specific region of pages.

The file that hFile specifies must be created with the GENERIC_READ and GENERIC_WRITE access rights.

PAGE_WRITECOPY Gives copy-on-write access to a specific region of pages.

The files that the hFile parameter specifies must be created with the GENERIC_READ and GENERIC_WRITE access rights.

PAGE_EXECUTE_READ Gives read and execute access to a specific region of pages.

The file specified by hFile must be created with the GENERIC_READ and GENERIC_EXECUTE access rights.

Windows Server 2003 and Windows XP: This feature is not available until Windows XP SP2 and Windows Server 2003 SP1.
PAGE_EXECUTE_READWRITE Gives read, write, and execute access to a specific region of pages.

The file that hFile specifies must be created with the GENERIC_READ, GENERIC_WRITE, and GENERIC_EXECUTE access rights.

Windows Server 2003 and Windows XP: This feature is not available until Windows XP SP2 and Windows Server 2003 SP1.

An application can specify section attributes by combining (using the bitwise OR operator) one or more of the following section attribute values with one of the preceding page protection values.

Value Meaning
SEC_COMMIT Allocates physical storage in memory or the paging file on disk for all pages of a section.

This is the default setting.

SEC_IMAGE Sets the file that is specified for section file mapping to be an executable image file.

Because the mapping information and file protection are taken from the image file, no other attributes are valid with SEC_IMAGE.

Windows Me/98/95: This flag is not supported.
SEC_NOCACHE Sets all pages of a section to non-cashable.

Applications should not use this flag except when explicitly required for a device. Using the interlocked functions with memory mapped by a SEC_NOCACHE section can result in an EXCEPTION_ILLEGAL_INSTRUCTION exception.

SEC_NOCACHE requires either the SEC_RESERVE or SEC_COMMIT to be set.

Windows Me/98/95: This flag is not supported.
SEC_RESERVE Reserves all pages of a section without allocating physical storage.

The reserved range of pages cannot be used by any other allocation operations until the range of pages is released.

Reserved pages can be identified in subsequent calls to the VirtualAlloc function. This attribute is valid only if the hFile parameter is INVALID_HANDLE_VALUE; that is, a file mapping object that the operating system paging file backs.

dwMaximumSizeHigh
[in] A high-order DWORD for the maximum size of a file mapping object.
dwMaximumSizeLow
[in] A low-order DWORD for the maximum size of a file mapping object.

If this parameter and dwMaximumSizeHigh are 0 (zero), the maximum size of the file mapping object is equal to the current size of the file that hFile identifies.

An attempt to map a file with a length of 0 (zero) fails with an error code of ERROR_FILE_INVALID. Applications should test for files with a length of 0 (zero) and reject those files.

lpName
[in] A pointer to a null-terminated string that specifies the name of a mapping object.

If this parameter matches the name of an existing mapping object that is named, the function requests access to the mapping object with the protection that flProtect specifies.

If this parameter is NULL, the mapping object is created without a name.

If lpName matches the name of an existing event, semaphore, mutex, waitable timer, or job object, the function fails, and the GetLastError function returns ERROR_INVALID_HANDLE. This occurs because these objects share the same namespace.

Terminal Services: The name can have a "Global\" or "Local\" prefix to explicitly create the object in the global or session namespace. The remainder of the name can contain any character except the backslash character (\). For more information, see Kernel Object Namespaces.
Windows XP: Fast user switching is implemented by using Terminal Services sessions. The first user to log on uses session 0 (zero), the next user to log on uses session 1 (one), and so on. Kernel object names must follow the guidelines that are outlined for Terminal Services so that applications can support multiple users.
Windows 2000: If Terminal Services is not running, the "Global\" and "Local\" prefixes are ignored. The remainder of the name can contain any character except the backslash character.
Windows NT: The name can contain any character except the backslash character.
Windows Me/98/95: The name can contain any character except the backslash character. An empty string ("") is a valid object name.

Return Values

If the function succeeds, the return value is a handle to the file mapping object.

If the object exists before the function call, the function returns a handle to the existing object (with its current size, not the specified size), and GetLastError returns ERROR_ALREADY_EXISTS.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

After a file mapping object is created, the size of the file must not exceed the size of the file mapping object; if it does, not all of the file contents are available for sharing.

If an application specifies a size for the file mapping object that is larger than the size of the actual named file on disk, the file on disk is increased to match the specified size of the file mapping object.

If the file cannot be increased, the result is a failure to create the file mapping object, and GetLastError returns ERROR_DISK_FULL.

The handle that CreateFileMapping returns has full access to a new file mapping object, and can be used with any function that requires a handle to a file mapping object. A file mapping object can be shared through process creation, handle duplication, or by name. For more information, see DuplicateHandle and OpenFileMapping.

Windows Me/98/95: File handles that are used to create file mapping objects must not be used in subsequent calls to file I/O functions, such as ReadFile and WriteFile. In general, if a file handle is used in a successful call to the CreateFileMapping function, do not use that handle until you close the corresponding file mapping object.

Creating a file mapping object creates the potential for mapping a view of the file, but does not map the view. The MapViewOfFile and MapViewOfFileEx functions map a view of a file into a process address space.

With one important exception, file views derived from a single file mapping object are coherent or identical at a specific time. If multiple processes have handles of the same file mapping object, they see a coherent view of the data when they map a view of the file.

The exception is related to remote files. Although CreateFileMapping works with remote files, it does not keep them coherent. For example, if two computers both map a file as writable, and both change the same page, each computer only sees its own writes to the page. When the data gets updated on the disk, it is not merged.

A mapped file and a file that is accessed by using the input and output (I/O) functions (ReadFile and WriteFile) are not necessarily coherent.

To fully close a file mapping object, an application must unmap all mapped views of the file mapping object by calling UnmapViewOfFile, and then close the file mapping object handle by calling CloseHandle.

These functions can be called in any order. The call to UnmapViewOfFile is necessary, because mapped views of a file mapping object maintain internal open handles to the object, and a file mapping object does not close until all open handles to it are closed.

Terminal Services sessions can use shared memory blocks to transfer data between processes those sessions spawn. If you do this, keep in mind that shared memory cannot be used in situations where both of the following conditions exist:

  • All of the processes that use a shared memory block are not spawned by one session.
  • All of the sessions share the same user logon credential.

To guard against an access violation, use structured exception handling to protect any code that writes to or reads from a memory mapped view. For more information, see Reading and Writing From a File View.

To have a mapping with executable permissions, an application must call CreateFileMapping with either PAGE_EXECUTE_READWRITE or PAGE_EXECUTE_READ, and then call MapViewOfFile with FILE_MAP_EXECUTE | FILE_MAP_WRITE or FILE_MAP_EXECUTE | FILE_MAP_READ.

Example Code [C++]

To implement a mapping object creation function that fails if the object already exists, an application can use the following code.

hMap = CreateFileMapping(...);

if (hMap != NULL && GetLastError() == ERROR_ALREADY_EXISTS)
{
CloseHandle(hMap);
hMap = NULL;
}
return hMap;

Example Code

Creating Named Shared Memory

To share data, multiple processes can use memory-mapped files that are backed by the system paging file.

First Process

The first process creates the file mapping object by calling the CreateFileMapping function with INVALID_HANDLE_VALUE and a name for the object. By using the PAGE_READWRITE flag, the process has read/write permission to the memory through any file views that are created.

Then the process uses the file mapping object handle that CreateFileMapping returns in a call to MapViewOfFile to create a view of the file in the process address space. The MapViewOfFile function returns a pointer to the file view.

When the process does not need access to the file mapping object, it should call the CloseHandle function. When all handles are closed, the system can free the section of the paging file that the object uses.

#include 
#include
#include

#define BUF_SIZE 256
TCHAR szName[]=TEXT("MyFileMappingObject");
TCHAR szMsg[]=TEXT("Message from first process");

void main()
{
HANDLE hMapFile;
LPCTSTR pBuf;

hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // max. object size
BUF_SIZE, // buffer size
szName); // name of mapping object

if (hMapFile == NULL || hMapFile == INVALID_HANDLE_VALUE)
{
printf("Could not create file mapping object (%d).\n",
GetLastError());
return;
}
pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
BUF_SIZE);

if (pBuf == NULL)
{
printf("Could not map view of file (%d).\n",
GetLastError());
return;
}


CopyMemory((PVOID)pBuf, szMsg, strlen(szMsg));
getch();

UnmapViewOfFile(pBuf);

CloseHandle(hMapFile);
}

Second Process

A second process can access the same data by calling the OpenFileMapping function with the same name as the first process. Then it can use the MapViewOfFile function to obtain a pointer to the file view.

#include 
#include
#include
#include

#define BUF_SIZE 256
TCHAR szName[]=TEXT("MyFileMappingObject");

void main()
{
HANDLE hMapFile;
LPCTSTR pBuf;

hMapFile = OpenFileMapping(
FILE_MAP_ALL_ACCESS, // read/write access
FALSE, // do not inherit the name
szName); // name of mapping object

if (hMapFile == NULL)
{
printf("Could not open file mapping object (%d).\n",
GetLastError());
return;
}

pBuf = MapViewOfFile(hMapFile, // handle to mapping object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
BUF_SIZE);

if (pBuf == NULL)
{
printf("Could not map view of file (%d).\n",
GetLastError());
return;
}

MessageBox(NULL, pBuf, TEXT("Process2"), MB_OK);

UnmapViewOfFile(pBuf);

CloseHandle(hMapFile);
}

Text Source:MSDN

2008年8月21日 星期四

時間格式化函數 strftime

strftime() 函數將時間格式化

我們可以使用strftime()函數將時間格式化為我們想要的格式。它的原型如下:

size_t strftime(

char *strDest,

size_t maxsize,

const char *format,

const struct tm *timeptr

);

我們可以根據format指向字符串中格式命令把timeptr中保存的時間信息放在strDest指向的字符串中,最多向strDest中存放maxsize個字符。該函數返回向strDest指向的字符串中放置的字符數。

函數strftime()的操作有些類似於sprintf():識別以百分號(%)開始的格式命令集合,格式化輸出結果放在一個字符串中。格式化命令說明串 strDest中各種日期和時間信息的確切表示方法。格式串中的其他字符原樣放進串中。格式命令列在下面,它們是區分大小寫的。

%a 星期幾的簡寫

%A 星期幾的全稱

%b 月分的簡寫

%B 月份的全稱

%c 標準的日期的時間串

%C 年份的後兩位數字

%d 十進製表示的每月的第幾天

%D 月/天/年

%e 在兩字符域中,十進製表示的每月的第幾天

%F 年-月-日

%g 年份的後兩位數字,使用基於周的年

%G 年分,使用基於周的年

%h 簡寫的月份名

%H 24小時制的小時

%I 12小時制的小時

%j 十進製表示的每年的第幾天

%m 十進製表示的月份

%M 十時製表示的分鐘數

%n 新行符

%p 本地的AM或PM的等價顯示

%r 12小時的時間

%R 顯示小時和分鐘:hh:mm

%S 十進制的秒數

%t 水平製表符

%T 顯示時分秒:hh:mm:ss

%u 每週的第幾天,星期一為第一天 (值從0到6,星期一為0)

%U 第年的第幾周,把星期日做為第一天(值從0到53)

%V 每年的第幾周,使用基於周的年

%w 十進製表示的星期幾(值從0到6,星期天為0)

%W 每年的第幾周,把星期一做為第一天(值從0到53)

%x 標準的日期串

%X 標準的時間串

%y 不帶世紀的十進制年份(值從0到99)

%Y 帶世紀部分的十制年份

%z,%Z 時區名稱,如果不能得到時區名稱則返回空字符。

%% 百分號

如果想顯示現在是幾點了,並以12小時制顯示,就像下面這段程序:

#include "time.h"

#include "stdio.h"

int main(void)

{

struct tm *ptr;

time_t lt;

char str[80];

lt=time(NULL);

ptr=localtime(<);

strftime(str,100,"It is now %I %p",ptr);

printf(str);

return 0;

}

其運行結果為:

It is now 4PM

而下面的程序則顯示當前的完整日期:

#include

#include

#include

int main( void )

{

struct tm *newtime;

char tmpbuf[128];

time_t lt1;



time( <1 );

newtime=localtime(<1);



strftime( tmpbuf, 128, "Today is %A, day %d of %B in the year %Y.\n", newtime);

printf(tmpbuf);



return 0;

}

利用C++ Builder進行精確計時

利用C++ Builder進行精確計時

雖然Win95下可視化開發工具如VC、Delphi、C++ Builder等都有專用的定時器控件Timer,而且使用很方便,可以實現一定的定時功能,但最小計時精度僅為55ms,且定時器消息在多任務操作系統中的優先級很低,不能得到及時響應,往往不能滿足實時控制環境下的應用。不過Microsoft公司



在Win32 API函數庫中已經為用戶提供了一組用於高精度計時的底層函數,如果用戶使用得當,計時精度可到1ms。這個計時精度、對於一般的實時系統控制完全可以滿足要求。現將由C++ Builder 4.0提供的重新封裝後的一組與時間相關的主要接口函數(函數名、參數、功能與Win32 API基本相同)說明如下:



  1.DWORD timeGetTime(void)

  返回從Windows啟動開始經過的毫秒數。最大值為232,約49.71

天。

  2.MMRESULT timeSetEvent(

  UINT uDelay,

  UINT uResolution,

  LPTIMECALLBACK lpTimeProc,

  DWORD dwUser,

  UINT fuEvent

   )



  該函數設置一個定時回調事件,此事件可以是一個一次性事件或週期性事件。事件一旦被激活,便調用指定的回調函數,成功後返回事件的標識符代碼,否則返回NULL。參數說明如下:



  uDelay:以毫秒指定事件的週期。

  UResolution:以毫秒指定延時的精度,數值越小定時器事件分辨率越高。缺省值為1ms。

  LpTimeProc:指向一個回調函數。

  DwUser:存放用戶提供的回調數據。

  FuEvent:指定定時器事件類型:

  TIME_ONESHOT:uDelay毫秒後只產生一次事件

  TIME_PERIODIC :每隔uDelay毫秒週期性地產生事件。



  3.MMRESULT timeKillEvent(UINT uTimerID)

  該函數取消一個指定的定時器回調事件。uTimerID標識要取消的事件(由timeSetEvent函數返回的標識符)。如果成功則返回TIMERR_NOERROR



,如果定時器時間不存在則返回MMSYSERR_INVALPARAM。

  void CALLBACK TimeProc(

  UINT uID,

  UINT uMsg,

  DWORD dwUser,

  DWORD dw1,

  DWORD dw2

   );



  該函數是一個應用程序定義的回調函數,出現定時器事件時該函數被調用。TimeProc是應用程序定義的函數名的佔位符。使用該函數時要注意



的是,它只能調用以下有限的幾組API函數:PostMessage,timeGetSystemTime, timeGetTime, timeSetEvent,timeKillEvent,midiOutShortMsg, midiOutLongMsg,OutputDebugString。同時也不要使用完成時間很長的API函數,程序儘可能簡短。



  使用以上一組函數就可以完成毫秒級精度的計時和控制(在C++Builder中使用時要將頭文件mmsystem.h加到程序中)。由於將定時控制精確到幾毫秒,定時器事件將佔用大量的CPU時間和系統資源,所以在滿足控制要求的前提下,應儘量將參數uResolution的數值增大。而且定時器實時控制功能完成後要盡快釋放。