jorge saraiva jorge saraiva - 1 month ago 5
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(){
signal(SIGINT,trata_sinal);
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?

thanks

Answer

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";
   a++;
   str[5] += a;
   write(1, str, strlen(str));
   if (a==5) {
       write(1, "bye", strlen("bye"));
       exit(0);
   }
}

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.