1.WAP to count the no. of characters,lines and words using file.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch,fname[10];
int count=0,count1=0,count2=0;
clrscr();
printf("Enter the file name:");
gets(fname);
fp=fopen(fname,"w");
while((ch=getchar())!=EOF)
{
fputc(ch,fp);
}
fclose(fp);
fp=fopen(fname,"r");
while((ch=fgetc(fp))!=EOF)
{
count++;
if(ch=='\n')
count1++;
if(ch=='\n'||ch==' ')
count2++;
}
printf("The no. of characters is:%d\n",count);
printf("The no. of lines i:%d\n",count1+1);
printf("The no. of words is:%d\n",count2+1);
fclose(fp);
getch();
}
2.WAP to save a file with information in binary format.
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int age;
};
void main()
{
FILE *fp;
struct student st1;
clrscr();
fp=fopen("xyz.bin","wb");
if(fp==NULL)
{
printf("File cannot open.");
getch();
exit();
}
printf("Enter the name:");
scanf("%s",st1.name);
printf("Enter the age:");
scanf("%d",&st1.age);
fwrite(&st1,sizeof(struct student),1,fp);
fclose(fp);
getch();
}
2.WAP to the saved read data from a binary file.
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int age;
};
void main()
{
FILE *fp;
struct student st1;
clrscr();
fp=fopen("xyz.bin","rb");
if(fp==NULL)
{
printf("File can't open");
getch();
exit();
}
fread(&st1,sizeof(struct student),1,fp);
printf("name=%s\n",st1.name);
printf("age=%d",st1.age);
fclose(fp);
getch();
}