The writing into a file operation is performed using the following pre-defined file handling methods.
- putc()
- putw()
- fprintf()
- fputs()
- fwrite()
putc( char, *file_pointer ) - This function is used to write/insert a character to the specified file when the file is opened in writing mode.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
char ch;
fp = fopen("D://program.txt","w");
putc('A',fp);
ch = 'B';
putc(ch,fp);
fclose(fp);
getch();
return 0;
}
Output
putw( int, *file_pointer ) - This function is used to writes/inserts an integer value to the specified file when the file is opened in writing mode.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
int i;
fp = fopen("D://program.txt","w");
putw(66,fp);
i = 100;
putw(i,fp);
fclose(fp);
getch();
return 0;
}
Output
fprintf( *file_pointer, "text" ) - This function is used to writes/inserts multiple lines of text with mixed data types (char, int, float, double) into specified file which is opened in writing mode.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
char *text = "\nThis is my Programming Blog";
int i = 10;
fp = fopen("D://program.txt","w");
fprintf(fp,"This is line1\nThis is line2\n%d", i);
fprintf(fp,text);
fclose(fp);
getch();
return 0;
}
Output
fputs( "string", *file_pointer ) - This method is used to insert string data into specified file which is opened in writing mode.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
char *text = "\nThis is my Programming Blog";
fp = fopen("D://program.txt","w");
fputs("Hi!\nHow are you?",fp);
fclose(fp);
getch();
return 0;
}
Output
fwrite( “StringData”, sizeof(char), numberOfCharacters, FILE *pointer ) - This function is used to insert specified number of characters into a binary file which is opened in writing mode.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
char *text = "Welcome to C Language";
fp = fopen("D://sample.txt","wb");
fwrite(text,sizeof(char),5,fp);
fclose(fp);
getch();
return 0;
}
Output
No comments:
Post a Comment