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()
Asked
Active
Viewed 3,018 times
-3

Marco
- 13
- 1
- 3
-
1Please always show us your effort when asking a question. What have you tried to prepare the decimal represenation and print it? – Gerhardh Jun 08 '18 at 09:20
-
Nit picking but `write()` is still a library function call and not a system call. – Ajay Brahmakshatriya Jun 08 '18 at 10:14
-
@AjayBrahmakshatriya Now that's *really* nitpicking! By that definition there are no system calls in C; they're available only to assembly-language programmers. – Steve Summit Jun 08 '18 at 12:51
-
@SteveSummit I agree. Maybe `sys_call` can be thought differently. But yes, I was taking it too literally. – Ajay Brahmakshatriya Jun 08 '18 at 13:01
1 Answers
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;
}

Soner from The Ottoman Empire
- 18,731
- 3
- 79
- 101

Achal
- 11,821
- 2
- 15
- 37
-
3I'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
-
-
2I 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
-