MCS-011 Problem Solving and Programming

  JHARKHAND BOARD You are here
Q1. Write a program to create a file in file handling. Solution: #include

#include

void main()

{

FILE *fp;

char say[80];

clrscr();

fp=fopen("test.txt","w");

if(fp==NULL)

{

printf("Cannot open file");

exit(0);

}

printf("Write the short assay:");

while(strlen(gets(say))>0)

{

fputs(say,fp);

}

fclose(fp);

getch();

}

Q2. Write a program to read the contents of one file and copy it into another file and count the number of character in that file. Solution: #include

#include

void main()

{

FILE *fp, *ft;

int noc=0;

char ch, ch1;

clrscr();

fp=fopen("ejaz/test.txt","r");

if(fp==NULL)

{

printf("Cannot open file");

exit(0);

}

ft=fopen("ejaz/test2.txt","ar");

if(ft==NULL)

{

printf("Cannot open file");

exit(0);

}

while(1)

{

ch=fgetc(fp);

if(ch==EOF)

break;

else

fputc(ch,ft);

}

fclose(ft);

ft=fopen("ejaz/test2.txt","a+");

if(ft==NULL)

{

printf("Cannot open file");

exit(0);

}

ch1=fgetc(ft);

while(ch1!=EOF)

{

noc++;

ch1=fgetc(ft);

}

printf("

The number of character in the file is :%d",noc);

fflush(ft);

fclose(ft);

fclose(fp);

getch();

}

Q3. Write a program to open a file and read its content. Solution: #include

#include

void main()

{

FILE *fp;

char ch;

clrscr();

fp=fopen("ejaz/test2.txt","r");

if(fp==NULL)

{

printf("Cannot open file");

exit(0);

}

else

do{

putchar(ch=fgetc(fp));

}while(ch!=EOF);

fclose(fp);

getch();

}