-3

For my project I must print an integer value without using function library (ex. itoa, sprintf, printf, fprintf, fwrite etc...), but I can use only system call write()

Marco
  • 13
  • 1
  • 3

1 Answers1

1

You want to print an integer number without using library function like printf, fwrite. You can use write() system call. Open manual page of write. It says

write() writes up to count bytes from the buffer starting at buf to the file referred to by the file descriptor fd.

ssize_t write(int fd, const void *buf, size_tcount);

For e.g

int num = 1234;
write(STDOUT_FILENO,&num,sizeof(num));

Or

write(1,&num,sizeof(num)); /* stdout --> 1  */

Above write() system call will write num into stdout stream.

Edit :- If your input is integer & your want to convert it into string & print it, but don't want to use library function like itoa() or sprintf() & printf(). For that you need to implement user define sprintf() & then use write().

int main(void) {
        int  num = 1234; 
        /* its an integer, you need to convert the given integer into
        string first, but you can't use sprintf()
        so impliment your own look like sprintf() */

        /*let say you have implimented itoa() or sprintf()
        and new_arr containg string 1234 i,e "1234"*/

        /* now write new_arr into stdout by calling write() system call */  
        write(1,new_arr,strlen(new_arr)+1);
        return 0;
}
Achal
  • 11,821
  • 2
  • 15
  • 37
  • 3
    I'm pretty sure the assignment was to print the number, say, 100 as the 3-character string `100`, not as the binary bytes `0x00 0x64` or some such. – Steve Summit Jun 08 '18 at 10:01
  • I misunderstood earlier. Thanks @SteveSummit I modified my answer. – Achal Jun 08 '18 at 15:54
  • 2
    I have undone my downvote. I would note, though, that (a) you've sort of helped user Marco cheat, by doing his homework for him, and (b) the answer boils down to writing the `itoa` function, which is itself a standard exercise, and which can be written considerably more straightforwardly. (You might want to do a web search to see some.) – Steve Summit Jun 08 '18 at 22:01
  • I understood @SteveSummit I'll be careful now onwards. – Achal Jun 08 '18 at 23:27