File Output in C Language | Write data into file in C Language | fputc(), putc(), putw(), fputs(), fprintf() function in C language
Different predefined functions of C language for file input/output are:
1. fputc()/putc() function
These functions are used to insert single character to a specified file.
Syntax:
fputc(C, Fpointer);
OR
putc(C, Fpointer);
C refers to character variable or constant whose value should be stored into a file.
Fpointer is the file pointer variable .
Program to demonstrate fputc()/putc(). |
#include<stdio.h> int main() { FILE *f1; char s; f1=fopen(“myfile.txt”,”w”); printf(“Enter any character:”); scanf(“%c”,&s); fputc(s,f1); //or putc(s,f1); fclose(f1); printf(“character stored in file”); return(0); } |
Output |
Enter any character :k character stored in file |
2. putw() function
putw() is used to insert an integer value to a file.
Syntax :
putw(Val, Fpointer);
Val refers to integer variable or constant whose value is to be written into a file.
Fpointer refers to the file pointer variable.
Program to demonstrate putw(). |
#include<stdio.h> int main() { FILE *f1; int n; f1=fopen(“integer.txt”,”w”); printf(“Enter any integer value:”); scanf(“%d”,&n); putw(n,f1); fclose(f1); printf(“Integer value inserted” ); return(0); } |
Output |
3. fputs() function
fputs() function is used to write a string value to a file.
Syntax:
fputs(S , Fpointer);
S represents the string variable or constant whose value is to be written into a file.
Fpointer represents file pointer variable.
Program to demonstrate fputs(). |
#include<stdio.h> int main() { FILE *f1; char n[100]; f1=fopen(“words.txt”,”w”); printf(“Enter a string=”); gets(n); fputs(n,f1); //inserstring value in file fclose(f1); printf(“\nstring stored in file”); return(0); } |
Output |
Enter a string=This is a string value string stored in file |
4. fprintf() function
This function is used to insert values of different types to a file.
Syntax:
fprintf(Fpointer,”Control-String”, var1,var2,….);
F is the file pointer variable used to refer a file.
Control-string contains conversion characters like %d, %f, %s to insert values of different data types into a file.
var1,var2,…. are variables or values we want to insert into file.
Program to demonstrate fprintf() function |
#include<stdio.h> int main() { FILE *f1; int empid; char ename[20]; f1=fopen(“emp.dat”,”w”); printf(“Enter employee id:”); scanf(“%d”,&empid); printf(“Enter employee name:”); fflush(stdin); gets(ename); fprintf(f1,”%d%s”,empid,ename); fclose(f1); return(0); } |
Output |
Enter employee id:101 Enter employee name:Sahil |