I'm trying to write an integer in stdout, in text form, with only write() function and possibly while/if.
I want to write the integer out in text form, so that it's human-readable, but actually it is write out in binary form :
Here is what I 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 I write the integer out in text form with only write (or putchar) and conditions ?
PS : I must not use other libraries, so I can't use printf or whatever !
My github : link
text mode
and binary mode
are common in computer science, but here is a reminder for ones who don't understand what I mean by text form
:
On a UNIX system, when an application reads from a file it gets exactly what's in the file on disk and the converse is true for writing. The situation is different in the DOS/Windows world where a file can be opened in one of two modes, binary or text. In the binary mode the system behaves exactly as in UNIX. However on writing in text mode, a NL (\n, ^J) is transformed into the sequence CR (\r, ^M) NL.
Quote from Cygwin.com
MAJ :
I found the 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;
}