简体   繁体   中英

How to use write() instead of printf()

I am trying to print something on the console just by using the syscall write(). So far, it is more difficult than I thought.

The function is kept simple:

void writeOutput(char a, int64_t b, uint8_t c) {
    char bNew[]; // what should be the size of that array=
    while(b != 0x0000000000000000) {
      int leftover = b%10;
      bNew[i] = intToChar(leftover);
      b = b/10;
      i++;
    }
}

char intToChar(int num) {
    return '0' + num;
}

a should be formatted as char, b as a decimal number and c as an octal number.

For example a possible input is: writeOutput('a', -0xffff, 17); // ouput is "a -65535 21"

The the printed arguments should be separated by spaces and terminated by a newline to standard output. Also, I am trying to do that without the the functions of the sprintf-family . This makes it a little bit trickier.

EDIT: My question is: How is it possible to do that with write()? (Sry, missed that!) The code is online. EDIT2: My main problem is doing it without using the sprintf-family. I hoped you might help me.

you can call the write() with first argument which is an fd as stdout. it will write to the stdout and which is your console. but before that you need have a string buffer for that you can use sprintf' or snprintf with the same formatting as printf`. but the printf way is easier and it should serve the purpose unless you have some very special use case.

#include <unistd.h> 
 
int main(void) { 
    write(1,"Hello World!", 12); 
    return 0; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM