Read ( r ) mode in C programming
In C programming, the "r"
mode is used to open a file for reading. It allows you to read data from the file, but not write to it.
Example 1:
Write
a C program to read a student's name, age, and percentage from the data file
"avn.dat" and display all the records on the screen.
Ans:
#include<stdio.h>
#include<conio.h>
main()
{
char
name[20];
int
age;
float
per;
FILE
*fp;
fp=fopen("d:\\avn.dat","r");
while(fscanf(fp,"%s%d%f",name,&age,&per)!=EOF)
{
printf("%s\t%d\t%f\n",name,age,per);
}
fclose(fp);
}
Example
2:
A
sequential data file"data.txt" has contents name post and salary
write a c program to count all the records from that data file.
#include
<stdio.h>
#include
<stdlib.h>
int
main(void)
{
//
Open the file for reading
FILE
*fp = fopen("data.txt", "r");
if (fp == NULL)
{
printf("Error
opening file!\n");
return
1
}
//
Initialize the record count to 0
int record_count = 0;
//
Read the name, post, and salary from the file
char
name[100];
char
post[100];
float
salary;
while
(fscanf(fp, "%s %s %f", name, post, &salary) == 3)
{
//
Increment the record count
record_count++;
}
//
Print the record count
printf("Number
of records: %d\n", record_count);
//
Close the file
fclose(fp);
return
0;
}
Example
3:
WAP which reads name,
department and age from the file named "employee.dat" and display
them on the monitor.
Ans:
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
char name[15],dep[20];
int a;
FILE *fp;
fp=fopen("employee.dat","r");
printf("employee name\t
Department\t\tAge");
printf("\n----------------------------------");
while(fscanf(fp,"%s%s%d",name,dep,&a)!=EOF)
{
printf("\n%s\t\t%s\t\t%d",name,
dep,a);
}
fclose(fp);
getch();
}
Example: 4
A
sequential data file emp.txt has contents name post and salary. Write a c program
to display all the records whose salary is more then 50000
#include
<stdio.h>
main()
{
char name[100];
char post[100];
FILE *fp = fopen("emp.txt",
"r");
while (fscanf(fp, "%s %s %d", name,
post, &salary) == 3)
{
if (salary > 50000)
{
printf("%s
%s %d\n", name, post, salary);
}
}
fclose(fp);
}
Example
5:
A sequential data file stuent.txt has
contains student name and marks of three subjects. Write a c program to display
all the passed students only. Assume pass marks is 35 in each subject.
#include <stdio.h>
#include
<stdlib.h>
#define
PASS_MARK 35
int
main()
{
char name[100];
int marks1, marks2, marks3;
while (fscanf(fp, "%s %d %d %d",
name, &marks1, &marks2, &marks3) == 4)
{
if (marks1 >= PASS_MARK && marks2 >= PASS_MARK && marks3 >= PASS_MARK)
{
printf("%s\n", name);
}
}
fclose(fp);
return 0;
No comments:
Post a Comment