Fahad Uddin Fahad Uddin - 2 months ago 8
C Question

How to implement puts() function?

I have tried to implement the puts function.It in actual returns a value but i cant get what should it return.please check my code and guide me further

/* implementation of puts function */
#include<stdio.h>
#include<conio.h>
void puts(string)
{
int i;
for(i=0; ;i++)
{
if(string[i]=='\0')
{
printf("\n");
break;
}
printf("%c",string[i]);

}

}

Answer

See comments in code.

int puts(const char *string)
{
    int i = 0;
   while(string[i])  //standard c idiom for looping through a null-terminated string
    {
        if( putchar(string[i]) == EOF)  //if we got the EOF value from writing the char
        { 
            return EOF;
        }
        i++;
    }
   if(putchar('\n') == EOF)  //this will occur right after we quit due to the null terminated character.
   {
       return EOF;
   }
   return 1; //to meet spec.
}

And, as an aside - I've written the equivalent of putc, puts several different times in relation to developing on embedded systems. So it's not always just a learning exercise. :)

Comment on EOF: It is a POSIX constant from stdio.h. In my Linux stdio.h, I have this definition:

/* End of file character.
   Some things throughout the library rely on this being -1.  */
#ifndef EOF
# define EOF (-1)
#endif

That definition code is GPL 2.1.