2

I'm a noob on C and trying to use write() function to show an integer.

These is my code:

int n = 7;
write(1, &n, 4);

I want to show 7, but the program shows nothing or other strange character when I set n to a big number.

What am I missing?

Kate Orlova
  • 3,225
  • 5
  • 11
  • 35
MattSales
  • 48
  • 1
  • 1
  • 4
  • write seems to be there to write ascii characters, not binary data (and try to display it as ascii!). Anyway, you should better use fprintf... Or convert your int to string before calling write – B. Go Oct 06 '19 at 17:57

5 Answers5

9

Objects like int are represented in memory with various bits. The write routine transmits exactly those bits of memory to its destination.

Terminals are not designed to display arbitrary bits of memory. They do not interpret the bits to mean an int or other object and then display that interpretation. Generally, we transmit characters to terminals. More specifically, we send codes that represent characters. Terminals are designed to receive these codes and display little pictures of writing (characters, glyphs, emoji, whatever).

To make a terminal display “7”, we need to send it the code for “7”. A common code system for characters is ASCII (American Standard Code for Information Interchange). The ASCII code for “7” is 55. So, if you do this:

char x = 55;
write(1, &x, 1);

then the terminal will draw “7” on its display, if ASCII is being used.

So write is the wrong routine to use to display int values for a human to read. Instead, you normally use printf, like this:

printf("%d", n);

The f in printf stands for formatted. It examines the bits that represent the value in n and formats the represented value as characters intended for humans to read, and then it writes those characters to standard output.

If you want to use write to transmit characters to the terminal, you can use sprintf to get just the formatting part of printf without the printing part. For starters, this code will work:

char buffer[80];                            // Make space for sprintf to work in.
int LengthUsed = sprintf(buffer, "%d", n);  // Format n in decimal.
write(1, buffer, LengthUsed);               // Write the characters.

(More sophisticated code would adapt the buffer size to what is needed for the sprintf.)

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • How can a decimal to ascii function could be written? – fp007 Jun 25 '21 at 13:11
  • @ferpalma21.eth See [here](https://stackoverflow.com/questions/190229/where-is-the-itoa-function-in-linux), [here](https://stackoverflow.com/questions/8257714/how-to-convert-an-int-to-string-in-c), or comments [here](https://stackoverflow.com/questions/69248148). – Steve Summit Sep 18 '22 at 13:01
2
void    ft_putnbr_fd(int nu, int fd)
{
    long int    n;

    n = nu;
    if (n < 0)
    {
        ft_putchar_fd('-', fd);
        n = n * (-1);
    }
    if (n < 10)
    {
        ft_putchar_fd(n + '0', fd);
    }
    else
    {
        ft_putnbr_fd(n / 10, fd);
        ft_putchar_fd(n % 10 + '0', fd);
    }
}
aloisdg
  • 22,270
  • 6
  • 85
  • 105
yo-ismaili
  • 21
  • 2
1

When you say something like

int n = 7;
write(fd, &n, sizeof(int));

you are taking the individual bytes corresponding to the integer n and writing them out to the file descriptor fd.

And that works just fine, unless what you wanted was a human readable representation of the integer n. That's the representation you'd get if you had instead written

printf("%d\n", n);

It's printf's job, when you use a format specifier like %d, to create a human-readable string of characters corresponding to a data object.

So if you want to print an int in a human-readable way, printf is definitely your best bet. If for some reason you can't use printf, you can use sprintf to create an in-memory string, then use write to write that out:

char tmpbuf[30];
sprintf(tmpbuf, "%d", n);
write(fd, tmpbuf, strlen(tmpbuf));

If for some reason you can't use sprintf, you might be able to use itoa:

char tmpbuf[30];
itoa(n, tmpbuf, 10);
write(fd, tmpbuf, strlen(tmpbuf));

However, the itoa function is not standard. If you don't have it or can't use it, your last resort would be to convert an integer to its string representation yourself, by hand. That's such a common question that I'm not going to provide Yet Another answer to it here, but see the linked question, or this one.

You didn't ask, but if there's ever the related problem of printing a floating point number using write, there are some hints in the comments at this question.

Steve Summit
  • 45,437
  • 7
  • 70
  • 103
0

When you want to print it out on the command prompt only use printf() instead:

int n = 7;
printf("%i",n);

Is there a special intention for using the write() function? If so, please add more of your code.

  • Yeah, I'm in a kind of test and I only can use write() – MattSales Oct 06 '19 at 18:11
  • 1
    @MattSales What do you want to achieve in general? because if you want to use `write()` there should be a fixed aim to go to. – RobertS supports Monica Cellio Oct 06 '19 at 18:14
  • @RoberS I have to create a function what show any given integer received as argument – MattSales Oct 06 '19 at 19:03
  • @MattSales Sorry for the delay. But you can do that easily with a sequence of `scanf()`and `printf()`: ` `scanf("%d",n); printf("%d,n"); ` Why you need to use the `write()` function only? homework? Because when it is homework, the given instructions should be accurate and possible to implement, but with `write()` in general there is no way to do what you want. that is what makes me wondering. – RobertS supports Monica Cellio Oct 07 '19 at 09:26
-1

Write function is a system call. It is used to write the content of a buffer to a declared output or to a stream. You should not use write. Instead, you must be using printf(" ", ...). In your case:

printf("%d", n);

or

print("%d\n",n);

if you want to write it on a line and do an end line(jump the next).

For more information about printf see: printf

Blackburn
  • 48
  • 4