Untitled
unknown
plain_text
10 months ago
2.8 kB
2
Indexable
Never
#include <stdio.h> #include <stdarg.h> #include <unistd.h> #include <stdlib.h> #include <math.h> //this function will go into a separate file //converting integer to strings char *its(int num) { //size of integer including '\0' int num_size; char *num_arr; num_size = (int)((ceil(log10(num))+1)*sizeof(char)); num_arr = malloc(num_size); if (!num_arr) return (NULL); sprintf(num_arr, "%d", num); return (num_arr); } //this function will go into a separate file int string_handler(va_list arg, char *ptr, int ptr_index) { char *str; str = va_arg(arg, char *); while (*str != '\0') { ptr[ptr_index] = *str; str++; ptr_index++; } return (ptr_index); } //this function will go into a separate file int int_and_dec_handler(va_list arg, char *ptr, int ptr_index) { int d; d = va_arg(arg, int); char *ptr2 = its(d); while (*ptr2 != '\0') { ptr[ptr_index] = *ptr2; ptr2++; ptr_index++; } free(its(d)); return (ptr_index); } //this function will go into a separate file int char_handler(va_list arg, char *ptr, int ptr_index) { char c; c = (char)va_arg(arg, int); ptr[ptr_index] = c; ptr_index++; return (ptr_index); } int _printf(const char * const format,...) { int i, buffer_index, bytes; char *buffer; va_list args; va_start(args, format); i = 0; buffer_index = 0; buffer = malloc(1024); if (!buffer) { perror("Memory allocation failure"); exit(EXIT_FAILURE); } while (format[i] != '\0') { if (format[i] == '%') { i++; if (format[i] == 'c') { int char_call = char_handler(args, buffer, buffer_index); buffer_index = char_call; } else if (format[i] == 's') { int str_call = string_handler(args, buffer, buffer_index); buffer_index = str_call; } else if (format[i] == '%') { buffer[buffer_index] = '%'; buffer_index++; } else if (format[i] == 'd' || format[i] == 'i') { int dec_call = int_and_dec_handler(args, buffer, buffer_index); buffer_index = dec_call; } } else { buffer[buffer_index] = format[i]; buffer_index++; } i++; } buffer[buffer_index] = '\0'; bytes = write(1, buffer, buffer_index); free(buffer); va_end(args); return (bytes); }
Leave a Comment