HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Struct to web style string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
stylestructstringweb

Problem

I've had to make several functions to turn some structures into strings. I am a still green when it comes C so I am unsure if I am doing this a very awkward way. The system I am coding for does not have snprintf, I know that would be far more elegant, however I cannot use it.
Any advice?

int device_to_string(char* const asString, pDevice dev, size_t maxLength)
{
  char* ipAsString;
  size_t actualLength;
  struct in_addr addr;

  if (dev == NULL)
  {
    return NULL_ERROR;
  }

  addr.s_addr = dev->ip;
  ipAsString = inet_ntoa(addr);

  actualLength = strlen("name=")  + strlen(dev->name) +
                 strlen("&ip=")   + strlen(ipAsString) +
                 strlen("&mac=")  + strlen(dev->mac)  +
                 strlen("&type=") + strlen(dev->type) + 1;

  if (actualLength > maxLength)
  {
    return SIZE_ERROR;
  }

  strncat(asString, "name=",    strlen("name="));
  strncat(asString, dev->name,  strlen(dev->name));
  strncat(asString, "&ip=",     strlen("&ip="));
  strncat(asString, ipAsString, strlen(ipAsString));
  strncat(asString, "&mac=",    strlen("&mac="));
  strncat(asString, dev->mac,   strlen(dev->mac));
  strncat(asString, "&type=",   strlen("&type="));
  strncat(asString, dev->type,  strlen(dev->type));

  asString[actualLength] = '\0';

  return NO_ERROR;
}

Solution

Yeah, without snprintf and sprintf it gets a bit tedious, but I think this code is actually quite clear. You use your horizontal and vertical whitespace very well, and it's clear what you're doing with each block of code. You have also controlled for any possible issues that might come up (null pointer, insufficient buffer length, etc). Maybe there's a more concise way to do it, but in terms of clarity and maintainability I think this code will suffice.

Context

StackExchange Code Review Q#365, answer score: 5

Revisions (0)

No revisions yet.