Sei sulla pagina 1di 3

SSN College of Engineering

Department of Computer Science and Engineering

Computer Practice Lab II

Exercise # 11
1. Sample Program to reading, writing to a file and printing the
contents of the file.

#include <stdio.h>

FILE *f1, *f2, *f3;


char rfn[10], wfn[10];

void readfile(void);
void writefile(void);
void printfile(void);

int main()
{
int ch;
printf("*************File operations Menu******************* \n");
printf("1. Read and Print file \n");
printf("2. Read and Write file \n");
printf("3. Print file \n");

printf("Enter Choice[1/2/3]\n");
scanf("%d", &ch);
switch(ch)
{
case 1:
readfile();break;
case 2:
writefile();break;
case 3:
printfile();break;
}

return 0;
}//main

void readfile()
{
printf("Enter the file name\n");
scanf("%s",rfn);

f1=fopen(rfn, "r");

while(!feof(f1))
printf("%c", fgetc(f1));
}//readfile
void writefile()
{
char c;

printf("Enter the file name to read\n");


scanf("%s",rfn);

printf("Enter the file name to write\n");


scanf("%s",wfn);

f1=fopen(rfn, "r");
f2=fopen(wfn, "w");

while(!feof(f1))
{
c= fgetc(f1);
fputc(c,f2);
}//while
}//readfile

void printfile()
{
printf("Enter the file name to print\n");
scanf("%s",rfn);

f1=fopen(rfn, "r");

while(!feof(f1))
printf("%c", fgetc(f1));
}//readfile

2. Sample program to do operations specified in a file.

#include <stdio.h>

FILE *in;
int main()
{
int op1,op2;
char oper;

in = fopen("oper.txt", "r");

while(!feof(in))
{
fscanf(in, "%d\t%c\t%d", &op1,&oper,&op2);
// printf("The got values are %d\t%c\t%d\n",op1,oper,op2);
switch(oper)
{
case '+':
printf("The Addition of %d and %d is %d\n", op1, op2,
op1+op2);
break;
case '*':
printf("The Multiplication of %d and %d is %d\n", op1, op2,
op1*op2);
break;
}//switch
}//while
fclose(in);
return 0;
}

Sample “oper.txt” file

5 + 10
5 * 12

3. Sample program for using command line execution in file


processing.

#include <stdio.h>

FILE *f1;

int main(int argc,char **argv)


{
if(argc!=2)
{
printf("Usage: mytype <filename> \n");
exit(0);
}

printf("File name to print\n");


printf("%s",argv[1]);

f1=fopen(argv[1], "r");

while(!feof(f1))
printf("%c", fgetc(f1));

return 0;
}//main

JOBS

Write a C program to simulate a QUIZ competition using file processing.

o 5 files each containing questions related a specific field


(example politics, sports, science and technology, general
aptitude and finance)
o A menu to list the options for type of questions

Potrebbero piacerti anche