Advertisement
Guest User

printf() and puts() wrappers for file descriptors

a guest
Apr 21st, 2012
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.86 KB | None | 0 0
  1. void sockputs(char* str, int sock) {
  2.         write(sock, str, strlen(str));
  3. }
  4. void sockprintf(int sock, const char *format, ...) {
  5.         //basically GNU asprintf
  6.         const unsigned buf_size = 16;
  7.         char* buf = (char*) malloc(sizeof(char) * buf_size);
  8.  
  9.         va_list vl;
  10.  
  11.     //first, try to vsnprintf to a buffer of length 16
  12.         va_start(vl, format);
  13.         unsigned len = vsnprintf(buf, buf_size, format, vl);
  14.         va_end(vl);
  15.  
  16.     //if that wasn't enough, allocate more memory and try again
  17.         if (len >= buf_size) {
  18.                 buf = (char*) realloc(buf, sizeof(char) * (len + 1));
  19.                 va_start(vl, format);
  20.                 vsnprintf(buf, len + 1, format, vl);
  21.                 va_end(vl);
  22.         }
  23.  
  24.         //output buf to the socket
  25.         sockputs(buf, sock);
  26.  
  27.         //free the buffer
  28.         free(buf);
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement