Files - 7 Demonstrating fprintf() function


/* Program to demonstrate the use of fprintf() function to store student details into the file */

#include< stdio.h >



/* To learn more about structures, http://sridhanvantari.blogspot.com/2013/10/structures.html */

struct student
{
int rno;
char name[30];
};


main()
{
FILE *fp;
char c;
int choice;
struct student s;





/* To learn more about fopen(), http://sridhanvantari.blogspot.com/2013/12/files-1-file-handling.html */
 

fp=fopen( "Yourname.txt","a");

do
{
 

  printf ( " \n Enter the rno, name : ");
  scanf( "%d%s", &s.rno, s.name);


/* To know more about syntax and parameters of fprintf(), http://sridhanvantari.blogspot.com/2013/12/fprintf-function-it-is-similar-to.html */

  fprintf( fp, "\n%2d%30s", s.rno,s.name);
  printf(" \n do u want to continue : ");
  scanf( "%d",&choice);
 

}while ( choice != 0 );

fclose(fp);
}

   In the above program initially we have declared a structure to hold the student details like rno and name. You can still expand the structure to hold more details. Variables are declared for pointer to file fp, a character variable c, an integer variable choice and a structure variable s to access structure  members.  Using fopen() function we are opening a file by name yourname.txt(you replace yourname with your own file name)  in append mode so that every time you add records will be added at the end of file. If we take write mode every time the program executed it overwrites the previously stored records hence we have taken append mode to preserve the previously entered records so that it can be later used to displaying or searching records. In a loop rno and name are accepted and using fprintf() function these details are written into file. In fprintf() function observe first we have written fp to indicate stream as fp (file stream) and format specifiers with width option and additional arguments s.rno and s.name whose values have to be written into the file. Then a message "do u want to continue :" will displayed and allows the user to input the choice, if the choice is other than zero it continue otherwise it quits the loop. At last file is closed using fclose(fp).

Comments