例如,在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 :(得分: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 "";
}