Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using write() to print to console

Tags:

c

So I am trying to create a function that uses the write() system call (printf and other options are not available) to output the string to the console. However, I hit a snag.

Here is my function:

static void doPrint (const char *s)
{
    write (STDOUT_FILENO, s, sizeof(s));
}

Which is being called by:

doPrint ("Hello World!\n");

However, it only prints out:

Hello Wo

What am I doing wrong?

Note: access to stdlib and stdio is restricted

Thanks

like image 734
Pat Avatar asked Jan 30 '26 02:01

Pat


1 Answers

In this context sizeof doesn't do what you want - it yields the size of the pointer, not the size of the string. Use strlen instead.

but access to the stdlib is restricted

You can roll your own using a while and a counter. Untested:

size_t my_strlen(const char *s)
{
    size_t len = 0;
    while (*s++)
        len++;

    return len;
}

or the slightly more efficient version:

size_t my_strlen(const char* s)
{
   const char *end = s;
   while (*end++) {};
   return end-s-1;
}

The above works because the pointer is advanced to the last position in the string and then the size is the difference between the last pointer location and the first pointer location, minus 1 of course to handle the null-terminating character.

like image 62
cnicutar Avatar answered Jan 31 '26 22:01

cnicutar