c - Writing an integer to stdout in text form using only write() to do writing -
i'm trying write integer in stdout, in text form, write() function , possibly while/if.
i want write integer out in text form, it's human-readable, write out in binary form :
here tried :
main.c :
#include "my_put_nbr.h" int main() { my_put_nbr(43); return 0; }
my_put_char.c :
#include <unistd.h> int my_put_nbr(int nb) { write(1, &nb, sizeof(nb)); return 0; }
so how can write integer out in text form write (or putchar) , conditions ?
ps : must not use other libraries, can't use printf or whatever !
my github : link
text mode
, binary mode
common in computer science, here reminder ones don't understand mean text form
:
on unix system, when application reads file gets what's in file on disk , converse true writing. situation different in dos/windows world file can opened in 1 of 2 modes, binary or text. in binary mode system behaves in unix. on writing in text mode, nl (\n, ^j) transformed sequence cr (\r, ^m) nl.
quote cygwin.com
maj :
i found answer:
#include "my_putchar.h" /* 0x2d = '-' * 0x0 = nul */ int my_put_nbr(int n) { if (n < 0) { my_putchar(0x2d); n = -n; } if (n > 9) { my_put_nbr(n/10); } my_putchar((n%10) + '0'); return 0; }
write writing, writing non-visible characters. can see with:
./myprogram | od -tx1
you need make number in n (int value 23) string "23" before printing it.
one way:
char buffer[16]; snprintf(buffer, sizeof(buffer), "%d", n); write(1, buffer, strlen(buffer));
Comments
Post a Comment