C programming putc stdio.h


In C programming the <stdio.h> putc function writes the character to the specified stream.The stream here can be file or console.The declaration of the function is given below.

int putc(int c, FILE *stream);

Parameters:
c -The characters to write to stream.

stream -The stream to which the the character ‘c’ is to be written.

Return type
int -Returns the character written.If a write error occurs,the error indicator for the stream is set and ‘putc’ returns EOF.

Note this function is same as ‘fputc‘ except ‘putc’ is implemented as a macro.Due to this reason also ‘putc’ has a disadvantage:the next section discuss the limitation.

Link : C fputc stdio.h

A code example is given below.

Code example

char str[] = “String written to file” ;

FILE *fp = fopen(“text.txt”, “w”);
unsigned int i = 0;

while (i < strlen(str) )
{
putc(str[i] , fp);
i++;
}

fclose(fp);

If the file ‘text.txt’ does not exist a new file with the name is created,if ‘text.txt’ does exist all the content is cleared and the string “String written to file” is written to it.





Disadvantage of using ‘putc’

The ‘putc’ is implemented as macro,this can introduce an unexpected behavior in your program.For instance it may evaluate the stream more than once and so we must make sure that the argument is not an expression with side effect or you can use ‘fputc’ which is more secure than ‘putc’.An example is given below.

Code example

char str[] = “abcdefghijklmnopqrstuvwxyz” ;

FILE *fp[19];
unsigned int i = 0;

while (i < 19 )
{
putc(str[i] , fp[i++]);
/*… evaluate the character written to the file or do anything with it*/
}

fclose( fp[0] );
fclose( fp[1] )

In the above program there is a chance that the same file will be evaluated twice or more and in such case some files will be left blank or not evaluated at all.A secure version of the above program is given below.

Code example

char str[] = “abcdefghijklmnopqrstuvwxyz” ;

FILE *fp[19];
unsigned int i = 0;

while (i < 19 )
{
putc(str[i] , fp[i]);
/*… evaluate the character written to the file or do anything with it*/
i++;
}

fclose( fp[0] );
fclose( fp[1] )

The ‘i’ is not incremented inside the stream which is passed as argument so this avoid evaluating the same argument twice.The best short cut to avoiding all this problems is by using ‘fputc’ function.

P.S. you must prefer ‘fputc’ over ‘putc’.


Related links

->C gets stdio.h

->C putchar stdio.h

->C fputc

->C fopen stdio.h

->C fclose stdio.h