The ones who are crazy enough to think they can change the world are the ones who do.- Steve Jobs
The following functions are used to write data into a file.
The fprintf() function is used to write sequence of characters, integers, floats, etc. by using appropriate format specifier specified data type.
Lets try to code using fprintf() and have some fun.
#include <stdio.h> int main() { FILE *fptr; //File pointer declaration char name[40]; int age; fptr = fopen("record.txt", "w "); //the function fopen opens the record text file printf("\nEnter your name : "); scanf("%s", name); printf("\nEnter your age : "); scanf("%d",&age); fprintf(fptr,"%s", name); //the entered name is written in to the file fprintf(fptr,"%d ", age); //the entered age is written to the file fclose(fptr); //the function closes the opened file return 0; }
The program shows that the fprintf function is used to store the name and age into the file record.txt.
The fputc() function also used to write into an opened file. But it writes a single character at a time.
Lets try to code using fputc() and have some fun.
#include <stdio.h> int main() { FILE *fptr; //File pointer declaration char ch; fptr = fopen("record.txt", "a "); //the function fopen opens the record text file printf("\nEnter characters with a space to write into a file press 'y 'to stop writing : "); scanf("%c",&ch); while(ch != 'y') { fputc(ch, fptr); scanf("%c",&ch); } fclose(fptr); //the function closes the opened file return 0; }
The program shows that the fputc function is used to store entered character through variable ch into the file record.txt.
The fputs() function used to write sequence of characters into file without the opened file. The fputs() function is used write a string into a file.
Lets try to code using fputs() and have some fun.
#include <stdio.h> int main() { FILE *fptr; //File pointer declaration char name[40], city[40]; fptr = fopen("record.txt", "w "); //the function fopen opens the record text file printf("\nEnter your name : "); scanf("%s", name); printf("\nEnter your city : "); scanf("%s", city); fputs(name, fptr); //the entered name is written in to the file fputs(city, fptr); //the entered age is written to the file fclose(fptr); //the function closes the opened file return 0; }
The program shows that the fputs function is used to store the name and age into the file record.txt.
We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.
© Copyright 2019