简体   繁体   中英

Is there easy way to do macro to string map?

For example,in Windows,if I want to make the error message of gethostbyname meaningful,I would need to manually map the error code to message, as follows,

#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;
}

Is there easy way to do this?

thanks.

I think you codes is in the easy way already, check the error code and return the error message. If you just want to make your codes more elegant, you could use an array of custom struct like below.

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 "";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM