Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write out a numeric value using low-level C

Tags:

c

i have a task where i need to pass a pointer to my function and display it in my function with "write".

#include <unistd.h>
#include <stdio.h>

void ft_ft(int *nbr){
    //printf("%d\n", *nbr);
    char c = *nbr;

    write(1, &c, 1);

}

int main(){
    int nbr = 42;
    ft_ft(&nbr);
}

as you can see i tried to make a int value into a char as taking the pointer from the parameter wouldn't work. on the other hand this doesn't either so could you help me?

the error msg:

[Running] (((the folder its in))) && gcc (((name of file)))... OUTPUT: * [Done] exited with code=0 in 0.046 seconds

so it actually ran the code but its not the output i would have wanted, what am i missing?

the printf() works fine but i can't get "write" to work.

thanks in advance

like image 646
7Ver7dict7 Avatar asked Jun 27 '26 23:06

7Ver7dict7


1 Answers

@CraigEstey how can i mark your comment as the answer ^? – 7Ver7dict7

Okay, here is the answer. To use write instead of printf, we can use snprintf and then write:

void
ft_ft(int *nbr)
{
    char buf[100];
    size_t len = snprintf(buf, sizeof buf, "%d\n", *nbr);
    write(1, buf, len);
}

In the event that any snprinf and related functions are also unacceptable, the following solution may suit:

void
ft_ft(int *nbr)
{
    char buf[100];

    // point past the end
    char *end = &buf[sizeof(buf)];

    // last valid place for a char
    char *beg = end - 1;

    // add newline to end
    *beg-- = '\n';

    // get copy
    int num = *nbr;

    // special case for zero
    if (num == 0)
        *beg-- = '0';

    // handle negative numbers
    int neg = (num < 0);
    if (neg)
        num = -num;

    // add digits from least significant to most significant
    for (;  num != 0;  num /= 10) {
        int dig = num % 10;
        *beg-- = dig + '0';
    }

    // add in minus sign
    if (neg)
        *beg-- = '-';

    // point to first char
    ++beg;

    // output final string
    write(1, beg, end - beg);
}
like image 112
Craig Estey Avatar answered Jun 30 '26 14:06

Craig Estey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!