The C fputc function is used to write the character(s) to the specified stream at the current position in a file, and then advanced the pointer position. In this article we will show you, How to write the character, or character array (string), or string data to a File using fputc in C Programming with example. Use fputs function to write complete string.
TIP: You have to include the #include<stdio.h> header before using this fputc function.
Syntax of fputc in C Programming
The syntax behind the fputc in C Programming language is as shown below.
1 |
int fputc(int char, FILE *stream) |
or we can simply write it as:
1 |
int fputc(int char, <File Pointer>) |
From the above code snippet,
- char: Please specify the character(s) you want to written to the file
- stream: Please specify the pointer to a FILE object, or simply say, file pointer that holds the file address and the operation mode
We are going to use the following specified file to demonstrate this fputc function.
From the above screenshot you can observe that, sample.txt file is in our Documents folder and it is empty.
fputc in C Programming Example
The fputc method is used to write character(s) to the user specified file. This C program will help you to understand the same.
C PROGRAM CODE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
// C fputc function example #include <stdio.h> #include<string.h> int main() { FILE *fileAddress; fileAddress = fopen("sample.txt", "w"); char name[50] = "Tutorial Gateway"; int i; int len = strlen(name); if (fileAddress != NULL) { for (i = 0; i < len; i++) { printf("Character we ar writing to the File = %c \n", name[i]); // Let us use our fputc fputc (name[i], fileAddress); } printf("\n We have written the Name successfully"); fclose(fileAddress); } else { printf("\n Unable to Create or Open the Sample.txt File"); } return 0; } |
OUTPUT
ANALYSIS
First we created the File pointer and then assigned the file in write mode.
TIP: Here we haven’t mentioned the full path of file name because my .c application and the text file resides in same location. If your scenario is different then, please provide the full path.
1 2 |
FILE *fileAddress; fileAddress = fopen("sample.txt", "w"); |
Next we used strlen function to find the string length
1 |
int len = strlen(name); |
Following If Statement will check whether we successfully opened the specified file or not.
1 |
if (fileAddress != NULL) { |
Next, we used the For Loop to traverse each and every character present in the name array
1 |
for (i = 0; i < len; i++) { |
Next, we used the fputc function to write each and every character present in the name array to the sample.txt file
1 |
fputc (name[i], fileAddress); |
Next, we are closing the file pointer.
1 |
fclose(fileAddress); |
Let us open the File to see whether we successfully returned the characters or not
Thank You for Visiting Our Blog
Share your Feedback, or Code!!