C PROGRAMMING
MULTIPLE CHOICE QUESTION
OLD QUESTION BANK
SAMPLE QUESTION 2080 AND SOLUTION

Formatted I/O (fscanf(), fprintf())

1. fscanf()

Definition: fscanf() is a standard C library function used for reading formatted data(mixed data like integer , float , character and string ) from a file.

Syntax:

fscanf(file_pointer, conversion specifier, & arguments);

Example:

WAP to open the file “abc.txt” created and read its contents (string and integer number ) and display them to the screen.(using fscanf() function)

#include<stdio.h>


int main()
{
FILE *fptr;
char str[200];
int num;
fptr = fopen("abc.txt", "r");
if(fptr==NULL)
{
printf("file cannot be open\n");
}
fscanf(fptr,"%[^\n]s,%d",str,num);
printf("%s%d",str,num);
fclose(fptr);
}

2. fprintf()

Definition: fprintf() is a standard C library function used for rwriting formatted data(mixed data like integer , float , character and string ) to a file.

Syntax:

fprintf(file_pointer, conversion specifier, arguments);

Example:

WAP  to create a file named student.txt in D:\ drive and write the name,roll,address and marks of a student to the file.


#include<stdio.h>

int main()
{
FILE *fptr;
char name[200];
int roll;
float marks;
fptr = fopen("abc.txt", "w");
if(fptr==NULL)
{
printf("file cannot be open\n");
}
printf("enter name,roll, marks ");
scanf("%s%d%f", name, &roll, &marks);
fprintf(fptr, "%s %d %f", name, roll, marks);
fclose(fptr);
}