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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With