-2

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;
}
noraj
  • 3,964
  • 1
  • 30
  • 38

1 Answers1

2

write is writing, but it is writing non-visible characters. You can see this with:

./myprogram | od -tx1

You will need to make the number in n (int value 23) into the string "23" before printing it.

One way:

  char buffer[16];
  snprintf(buffer, sizeof(buffer), "%d", n);
  write(1, buffer, strlen(buffer));
John Hascall
  • 9,176
  • 6
  • 48
  • 72
  • the number is `42` `$ ./main.out` => output : `�Ð�` and `$ ./main.out | od -tx1` => output : `0000053` – noraj Jan 07 '16 at 17:51
  • John Hascall : i don't want to use snprintf(), just write() – noraj Jan 07 '16 at 17:56
  • 2
    Then you will need to write the code to do the conversion to a string yourself. This page should help http://stackoverflow.com/a/9660930/2040863 – John Hascall Jan 07 '16 at 17:59
  • 1
    *i don't want to use snprintf(), just write()* Why do you expect writing a raw binary `int` to a character-based terminal to be readable? – Andrew Henle Jan 07 '16 at 18:00
  • @AndrewHenle I just re-coded `putchar`, `puts` and `strlen` with only write or/and boucle (while)or/and conition (if). I now want to write a put_int with just write() and ascii translation. I fact I want to use only system call and no additionnal library. – noraj Jan 07 '16 at 18:20
  • [Github](https://github.com/shark-oxi/my_functions) : here it is what I'm doing – noraj Jan 07 '16 at 18:36