How to write integers with write() function in C? [duplicate]

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?

3,283 5 5 gold badges 14 14 silver badges 36 36 bronze badges asked Oct 6, 2019 at 17:46 48 1 1 gold badge 1 1 silver badge 5 5 bronze badges

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

Commented Oct 6, 2019 at 17:57

5 Answers 5

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 .)