—————————
你會處理出錯資訊嗎?哦,它並不是簡單的輸出。看下面的樣本:
if ( p == NULL ){
printf ( "ERR: The pointer is NULL/n" );
}
告別學生時代的編程吧。這種編程很不利於維護和管理,出錯資訊或是提示資訊,應該統一處理,而不是像上面這樣,寫成一個“寫入程式碼”。第10條對這方面的處理做了一部分說明。如果要管理錯誤資訊,那就要有以下的處理:
/* 聲明出錯代碼 */
#define ERR_NO_ERROR 0 /* No error */
#define ERR_OPEN_FILE 1 /* Open file error */
#define ERR_SEND_MESG 2 /* sending a message error */
#define ERR_BAD_ARGS 3 /* Bad arguments */
#define ERR_MEM_NONE 4 /* Memeroy is not enough */
#define ERR_SERV_DOWN 5 /* Service down try later */
#define ERR_UNKNOW_INFO 6 /* Unknow information */
#define ERR_SOCKET_ERR 7 /* Socket operation failed */
#define ERR_PERMISSION 8 /* Permission denied */
#define ERR_BAD_FORMAT 9 /* Bad configuration file */
#define ERR_TIME_OUT 10 /* Communication time out */
/* 聲明出錯資訊 */
char* errmsg[] = {
/* 0 */ "No error",
/* 1 */ "Open file error",
/* 2 */ "Failed in sending/receiving a message",
/* 3 */ "Bad arguments",
/* 4 */ "Memeroy is not enough",
/* 5 */ "Service is down; try later",
/* 6 */ "Unknow information",
/* 7 */ "A socket operation has failed",
/* 8 */ "Permission denied",
/* 9 */ "Bad configuration file format",
/* 10 */ "Communication time out",
};
/* 聲明錯誤碼全域變數 */
long errno = 0;
/* 列印出錯資訊函數 */
void perror( char* info)
{
if ( info ){
printf("%s: %s/n", info, errmsg[errno] );
return;
}
printf("Error: %s/n", errmsg[errno] );
}
這個基本上是ANSI的錯誤處理實現細節了,於是當你程式中有錯誤時你就可以這樣處理:
bool CheckPermission( char* userName )
{
if ( strcpy(userName, "root") != 0 ){
errno = ERR_PERMISSION_DENIED;
return (FALSE);
}
...
}
main()
{
...
if (! CheckPermission( username ) ){
perror("main()");
}
...
}
一個即有共性,也有個性的錯誤資訊處理,這樣做有利同種錯誤出一樣的資訊,統一使用者介面,而不會因為檔案開啟失敗,A程式員出一個資訊,B程式員又出一個資訊。而且這樣做,非常容易維護。代碼也易讀。
當然,物極必反,也沒有必要把所有的輸出都放到errmsg中,抽取比較重要的出錯資訊或是提示資訊是其關鍵,但即使這樣,這也包括了大多數的資訊。