The syntax of the
fputc() function is as follows:
int fputc(int ch, FILE *fp);
fputc() function is used to write a single character specified by the first argument to a text file pointed by the fp pointer. After writing a character to the text file, it increments the internal position pointer. If the write is successful, it returns the ASCII value of the character that was written. On error, it returns
Although, the formal definition of
fputc() says “it writes a single character to the file” that’s not how it is implemented. In practice writing a single character one by one would be very inefficient and slow. Instead if writing characters one by one into the file, they are accumulated in a buffer memory. Once the number of characters reaches a reasonable number, they are written to the file in one go.
Let’s take an example.
The following program demonstrates how to use
fp = fopen("myfile.txt", "w");
if(fp == NULL)
printf("Error opening file\n");
printf("Press Ctrl+Z in DOS and Ctrl+D\n\
in Linux to stop reading more characters\n\n");
printf("Enter text: ");
while( (ch=getchar()) != EOF )
Press Ctrl+Z in DOS and Ctrl+D
in Linux to stop reading more characters
Enter text: Testing fputc()
How it works:
In line 6, a variable
ch of type
int is declared.
In line 7, a structure pointer variable
fp of type
struct FILE is declared.
In line 8,
fopen() function is called with two arguments namely
"w". On success, it returns a pointer to file
myfile.txt and opens the file
"myfile.txt" in write-only mode. On failure, it returns
In line 10, if statement is used to test the value of fp. If it is
printf() statement prints the error message and program terminates. Otherwise, the program continues with the statement following the if statement.
In lines 16 and 19,
printf() statements prints the strings to the console.
In line 21, a while loop is used in conjunction with
getchar(). The while loop reads the character from the standard input and writes it to the file. Notice the condition of the while loop:
(ch=getchar()) != EOF
The parentheses around the ch=getchar() is necessary because the precedence of
!= operator is greater than that of
The while loop will keep reading characters from the standard input until Ctrl+Z in Windows or Ctrl+D is Linux is entered. Recall that
getchar() function returns the ASCII value of character just read from the standard input and
EOF when an end of file character is encountered. As soon as you enter the end of file character the condition evaluates to false and the control breaks out of the while loop.
In line 26,
fclose() function is called to close the file.
It is important to note that the character ^Z is not written to the file.