You are on page 1of 5

WEEK 12- LAB B

Ans1.)#include <stdio.h>
int main(){
FILE *fptr;
char sentence[30];
fptr=fopen("sent.txt","w");
fprintf(fptr,"This is the content of the test file");
printf("Input a sentence for the file:");
gets(sentence);
fclose(fptr);
printf("\nThe content of test file is created successfully...!!");
}

Ans2.) #include <stdio.h>


#include <stdlib.h>
int main(){
FILE *fptr;
char fname[20];
char fcontent;
printf("Input the filename to be
opened:"); scanf("%s",fname);
fptr=fopen(fname,"r");
if(fptr==NULL){
printf("File does not exist or cannot be opened.\n");
exit(0);
}
printf("\nThe content of the file %s is:",fname);
fcontent=fgetc(fptr);
while(fcontent!=EOF){
printf("%c",fcontent);
fcontent=fgetc(fptr);
}
fclose(fptr);
return 0;
}

Ans3.) #include <stdio.h>


int main(){
FILE *fptr;
int i,n;
char fcont[100];
char fname[20]="multi.txt";
char fcont1;
printf("Input the number of lines to be written:");
scanf("%d", &n);
printf("::The lines are::\n");
fptr=fopen(fname,"w");
for(i=0;i<n+1;i++){
fgets(fcont,sizeof fcont,stdin);
fputs(fcont,fptr);
}
fclose(fptr);
fptr=fopen(fname,"r");
printf("\nThe content of the file %s is:",fname);
fcont1=fgetc(fptr);
while(fcont1!=EOF)
{ printf("%c",fcont1);
fcont1=fgetc(fptr);
}
fclose(fptr);
return 0;
}

Ans4.) #include<stdio.h>
int main(){
FILE *fptr;
int num=0;
char fname[40],str;
printf("Enter file name:");
scanf("%s",fname);
fptr=fopen(fname,"r");
str=getc(fptr); while(str!
=EOF){
if(str=='\0');
{ num++;
}
str=getc(fptr);
}
fclose(fptr);
printf("There are %d lines in %s",num,fname);
return 0;
}

Ans5.) #include <stdio.h>


#include <stdlib.h>
int main(){
FILE *fsring1,*fsring2,*ftemp;
char ch,file1[20],file2[20],file3[20];
printf("Enter name of first file:");
gets(file1);
printf("Enter name of second file:");
gets(file2);
printf("Enter name to store merged file:");
gets(file3);
fsring1=fopen(file1,"r");
fsring2=fopen(file2,"r");
if (fsring1 == NULL || fsring2 == NULL)
{ perror("Error has occured");
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
ftemp=fopen(file3,"w");
if (ftemp == NULL){
perror("Error has occured");
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
while((ch=fgetc(fsring1))!=EOF)
fputc(ch,ftemp);
while ((ch=fgetc(fsring2))!=EOF)
fputc(ch,ftemp);
printf("Two files merged as %s successfully.",file3);
fclose(fsring1);
fclose(fsring2);
fclose(ftemp);
return 0;
}

You might also like