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
sizeofdoesn’t do what you want – it yields the size of the pointer, not the size of the string. Usestrleninstead.You can roll your own using a
whileand a counter. Untested:or the slightly more efficient version:
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.