C-Programming

Formatted Disk I/O Functions in file

For formatted reading and writing of characters, strings, integers, float, there exist two functions:

fscanf( ) and fprintf( ):

The uses of these functions are same as in the case of console input and output. The fscanf ( ) function is used to read the data from the file and fprintf( ) is used write the data on the file. These functions take the following syntaxes:

fscanf(file_pointer,”formal string”, argument);

fprintf(file_pointer,”formal string”, argument);

 Here is a sample program which illustrates the use of these functions.

Programs to write information to a file and read from using formatted Input/Output.

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

main()

{

char choice;

char name[40];

int age;

float height;

FILE *fp;

fp=fopen(“myname.text”,”w+”);

do

{

printf(“\nEnter name”);

scanf(“%s”,name);

fflush(stdin);

printf(“\nEnter age”);

scanf(“%d”,&age);

fflush(stdin);

printf(“\n Enter height”);

scanf(“%f”,&height);

fflush(stdin);

printf(“\n do you wish to continue”);

scanf(“%c”,&choice);

fprintf(fp,”%s\t%d\t%f”,name,age,height);

}

while(choice= =’y’|| choice= =’y’);

rewind(fp);

while(!feof(fp))

{

fscanf(fp,”%s%d%f”,name,&age,&height);

printf(“\n%s\t%d\t%0.2f”,name,age,height);

}

fclose(fp);

getch();

}

In this program the function fprintf() writes the values of three variables to the file. This function is similar to print(), except that a FILE pointer is included as the first argument .The function fflush() must be the designed to remove or flush out any data remaining in the buffer . The argument to fflush() must be the buffer which we want to flush out . Here we use stdin ,which means buffer related with standard input device, the keyboard. The fscanf() function is used to read the data from the disk. This function is similar to scanf() , except that, as with fprintf(), a pointer to FILE is included as the first argument.

Using rewind ( ) function (Prev Lesson)
(Next Lesson) Record Input/Output functions in file
Back to C-Programming

No Comments

Post a Reply

Teacher
Bhim Gautam
Role : Lecturer
Read More
error: Content is protected !!