jorge saraiva jorge saraiva - 7 months ago 34
C Question

How can i use system function 'write' instead of 'printf' from stdio.h library?

For example

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

int a = 0;
void trata_sinal(int s) {
a++; printf("ouch %d ",a); fflush(stdout);
if (a==5) {printf("bye"); exit(0);}

int main(){
while(1) pause();
return 0;

Its not possible to write directly on stdout with write function in this case? I can't print out on screen with write when i want to print out variables?



In this specific case, you can start with a string to use as a template, modify it, then pass it to write.

void trata_sinal(int s) {
   char str[] = "ouch 0";
   str[5] += a;
   write(1, str, strlen(str));
   if (a==5) {
       write(1, "bye", strlen("bye"));

This is taking advantage of the fact that the value of a will not be larger than 9 and that the character codes for the digits 0 - 9 are consecutive.