Skip to content

Instantly share code, notes, and snippets.

@rfc-2549
Created January 31, 2022 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rfc-2549/e47baf2a114385148562b30d9aaaa528 to your computer and use it in GitHub Desktop.
Save rfc-2549/e47baf2a114385148562b30d9aaaa528 to your computer and use it in GitHub Desktop.
#include <unistd.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
int vfdprintf(int fd, const char *fmt, va_list ap)
{
va_list args;
char *str = NULL;
va_copy(args, ap);
int size = vsnprintf(NULL, 0, fmt, args) + 1; /* For '\0' */
/* if negative number is returned return error */
if(size < 0)
return -1;
str = (char *)malloc(size);
if(str == NULL)
return -1;
va_end(args);
vsprintf(str, fmt, ap);
write(fd, str, size + 1);
free(str);
return size;
}
int
fdprintf(int fd, const char *fmt, ...)
{
va_list args;
int size = 0;
va_start(args, fmt);
size = vfdprintf(fd,fmt,args);
va_end(args);
return size;
}
int
main(void)
{
int fd = open("hello.txt",O_RDWR);
fdprintf(fd,"hello world %i %s %X\n", 42, "spurdo sparde", 2147483647);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment