
int putstring(const char *s)
{
int count=0; /*used to calcular how many bytes will be written*/
const char *p=s; /*pointer used to find terminating zero of string*/
while(*++p){} /*loop until zero found and immediately exit*/
count=p-s; /*count is the difference of pointers p and s*/
fwrite(s,1,count,stdout); /*https://cppreference.com/w/c/io/fwrite.html*/
return count; /*return how many bytes were written*/
}
The putstring function is the foundation of chastelib because being able to output something to the screen is important. This function was written for a consistent interface independent of which programming language or library I am using. It manually finds the length of the string and then writes it to standard output.
This update to the tiny function includes detailed comments nicely lined up. I also changed the return type to an integer for reasons that will become apparent in other programs. Keeping track of how many bytes are printed is now possible by capturing the return value. Of course, if I don’t need this, I ignore it and then it has the same functionality as the original void function.
Although most nerds won’t understand the need for this, it is written for clarity of how I understand C strings as character arrays. They are best handled with raw pointers and that is why C and C++ are supreme in my opinion because they allow this. In a future post, I may explain the relevance this also has to do with the ncurses library which I have been messing around with lately. Each day I am thinking about a text based game I want to write.
Leave a comment