8. Write a C program that uses functions to perform the following operations:
a)Count number of characters, words in a file.
b) Write a C program to reverse the first n characters in a file.
(Note: The file name and n are specified on the command line.)
c) Write a C program which copies one file to another.
Flowcharts
Programs :
8(a)
#include<stdio.h>
main()
{
char ch;
int nc=0,nb=0,nl=0,nt=0;
FILE *pf;
pf=fopen("First.txt","r");
if(pf==NULL)
{
puts("Cant open");
exit(1);a
}
while(1)
{
ch=fgetc(pf);
if(ch==EOF)
break;
nc++;
if(ch==' ')
nb++;
if(ch=='\n')
nl++;
if(ch=='\t')
nt++;
}
printf("nc =%d,nb =%d,nl =%d,nt =%d\n",nc,nb,nl,nt);
printf("No of Words are %d",nb+1);
fclose(pf);
}
or
#include<stdio.h>
void main()
{
FILE *fp;
int c,count=0;
printf("Enter the chars:\n");
printf("Press ctrl+Z to stop entry\n");
fp=fopen("enter.txt","w");
while((c=getchar())!=EOF)
fputc(c,fp);
fclose(fp);
printf("\n");
fp=fopen("enter.txt","r");
while((c=fgetc(fp))!=EOF)
{
printf("%c",(char)c);
++count;
}
fclose(fp);
printf("\nThe no of chars in the file are %d",count);
}
a)Count number of characters, words in a file.
b) Write a C program to reverse the first n characters in a file.
(Note: The file name and n are specified on the command line.)
c) Write a C program which copies one file to another.
Flowcharts
8(a)
#include<stdio.h>
main()
{
char ch;
int nc=0,nb=0,nl=0,nt=0;
FILE *pf;
pf=fopen("First.txt","r");
if(pf==NULL)
{
puts("Cant open");
exit(1);a
}
while(1)
{
ch=fgetc(pf);
if(ch==EOF)
break;
nc++;
if(ch==' ')
nb++;
if(ch=='\n')
nl++;
if(ch=='\t')
nt++;
}
printf("nc =%d,nb =%d,nl =%d,nt =%d\n",nc,nb,nl,nt);
printf("No of Words are %d",nb+1);
fclose(pf);
}
or
#include<stdio.h>
void main()
{
FILE *fp;
int c,count=0;
printf("Enter the chars:\n");
printf("Press ctrl+Z to stop entry\n");
fp=fopen("enter.txt","w");
while((c=getchar())!=EOF)
fputc(c,fp);
fclose(fp);
printf("\n");
fp=fopen("enter.txt","r");
while((c=fgetc(fp))!=EOF)
{
printf("%c",(char)c);
++count;
}
fclose(fp);
printf("\nThe no of chars in the file are %d",count);
}
8(b)
/* Write a C program to reverse the first n characters in a file.
(Note: The file name and n are specified on the command line.)*/
#include <stdio.h>
#include <string.h>
void main(int argc, char *argv[])
{
char a[15];
char s[20];
char n;
int k;
int j=0;
int i;
int len;
FILE *fp;
if(argc!=3)
{
puts("Improper number of arguments.");
exit(0);
}
fp = fopen(argv[1],"r");
if(fp == NULL)
{
puts("File cannot be opened.");
exit(0);
}
k=*argv[2]-48;
n = fread(a,1,k,fp);
a[n]='\0';
len=strlen(a);
for(i=len-1;i>=0;i--)
{
s[j]=a[i];
printf("%c",s[j]);
j=j+1;
}
s[j+1]='\0';
}
8(c)
#include<stdio.h>
main()
{
char ch;
FILE *pf,*fp;
pf=fopen("First.txt","r");
fp=fopen("Second.txt","w");
if(pf==NULL)
{
puts("Cant open for reading");
exit(1);
}
if(fp==NULL)
{
puts("Cant open for Writing");
exit(1);
}
while(1)
{
ch=fgetc(pf);
if(ch==EOF)
break;
printf("%c",ch);
fputc(ch,fp);
}
fclose(pf);
fclose(fp);
}



Comments
Post a Comment