2009-11-12 48 views
0

例如,在Windows中,如果我想要的gethostbyname有意義的錯誤信息,我需要手動映射錯誤代碼信息,如下所示,有沒有簡單的方法來做宏到字符串映射?

#include <stdio.h> 
#include <winsock2.h> 
#pragma comment(lib, "ws2_32.lib") 

int 
main(void) 
{ 
struct hostent *host; 
WSAData wsaData; 
int errcode; 

if (WSAStartup(MAKEWORD(2, 2), &wsaData)) { 
    perror("WSAStartup failed"); 
    exit(-1); 
} 

host = gethostbyname("www.google.com"); 

if (host != NULL) { 
    printf("the offical name of the host is: %s\n", host->h_name); 
} else { 
    errcode = WSAGetLastError(); 
    printf("the error code is %d\n", errcode); 
    if (errcode == WSAENETDOWN) 
    perror("network down"); 
    else if (errcode == WSANOTINITIALISED) 
    perror("call WSAStartup before"); 
    else if ... 
    perror("gethostbyname failed"); 
    return -1; 
} 

return 0; 
} 

有沒有簡單的方法來做到這一點?

謝謝。

回答

0

我覺得你的代碼已經很簡單了,檢查錯誤代碼並返回錯誤信息。如果你只是想讓你的代碼更優雅,你可以使用像下面這樣的自定義結構數組。

struct ErrorInfo 
{ 
    int Code; 
    const char* Message; 
}; 

ErrorInfo* errorMap = 
{ 
    { WSAENETDOWN,  "network down" }, 
    { WSANOTINITIALISED, "call WSAStartup before" }, 
}; 

const char* GetErrorMessage(int errorCode) 
{ 
    for(int i=0; i<sizeof(errorMap)/sizeof(ErrorInfo)); i++) 
    { 
    if(errorMap[i].Code == errorCode) 
     return errorMap[i].Message; 
    } 
    return ""; 
} 
相關問題