fputc() — Write a character
Standards
Standards / Extensions | C or C++ | Dependencies |
---|---|---|
ISO C
POSIX.1 XPG4 XPG4.2 C99 Single UNIX Specification, Version 3 Language environment |
both |
Format
#include <stdio.h>
int fputc(int c, FILE *stream);
#define _OPEN_SYS_UNLOCKED_EXT 1
#include <stdio.h>
int fputc_unlocked(int c, FILE *stream);
General description
Converts c to
an unsigned char
and then writes c to
the output stream pointed to by stream at
the current position and advances the file position appropriately.
The fputc() function is identical to putc but
is always a function, because it is not available as a macro.
If the stream is opened with one of the append modes, the character is appended to the end of the stream regardless of the current file position.
The fputc() function is not supported for files opened
with type=record
or type=blocked
.
fputc() has the same restriction as any write operation for a read immediately following a write, or a write immediately following a read. Between a write and a subsequent read, there must be an intervening flush or reposition. Between a read and a subsequent write, there must also be an intervening flush or reposition unless an EOF has been reached.
fputc_unlocked() is functionally equivalent to fputc() with the exception that it is not thread-safe. This function can safely be used in a multithreaded application if and only if it is called while the invoking thread owns the (FILE*) object, as is the case after a successful call to either the flockfile() or ftrylockfile() function.
Returned value
If successful, fputc() returns the character written.
If unsuccessful, fputc() returns EOF.
Example
/* CELEBF34
This example writes the contents of buffer to a file called
myfile.dat.
Because the output occurs as a side effect within the second
expression of the for statement, the statement body is null.
*/
#include <stdio.h>
#define NUM_ALPHA 26
int main(void)
{
FILE * stream;
int i;
int ch;
char buffer[NUM_ALPHA + 1] = "abcdefghijklmnopqrstuvwxyz";
if (( stream = fopen("myfile.dat", "w"))!= NULL )
{
/* Put buffer into file */
for ( i = 0; ( i < sizeof(buffer) ) &&
((ch = fputc( buffer[i], stream)) != EOF ); ++i );
fclose( stream );
}
else
printf( "Error opening myfile.dat\n" );
}