Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1. The program cp.c makes a copy of a file. It uses getc () and putc () to do th

ID: 3635093 • Letter: 1

Question

1. The program cp.c makes a copy of a file. It uses getc () and putc () to do the input and output. Write four new versions of a file copy program. Each of the programs should have the same functionality as cp.c

a. In the first version, use fgetc () to do the input and fputc () to do the output.

b. In the second version, use fgets () to do the input and fputs () to do the output.

c. In the third version, use fread () to do the input and fwrite () to do the output.

d. In the fourth version, use fscanf () to do the input and fprintf () to do the output.

e. Compare the sizes of the object code from all five versions of the file copy programs. If the facilities for testing execution efficiency are available on your system, test the efficiency of each version. Report on your findings.

Explanation / Answer

Dear, a) fgetc ,fputc both functions reads(from file) and outputs character /* file.c: Display contents of a file on screen */ #include void main() { FILE *fopen(), *fp; int c ; fp = fopen( “prog.c”, “r” ); c = fgetc( fp ) ; while ( c != EOF ) { fput(c,stdout); c = getc ( fp ); } fclose( fp ); } b) #include int main() { // open the file "fred.txt" for reading FILE *in = fopen("fred.txt", "rt"); FILE *out = fopen("fwrite.txt", "wt"); // read the first line from the file char buffer[100]; fgets(buffer, 20, in); fputs(buffer,out); // close the stream fclose(out); fclose(in); return 0; } c) The function fread reads nmemb objects, each size bytes long, from the stream pointed to by stream, storing them at the location given by ptr. The function fwrite writes nmemb objects, each size bytes long, to the stream pointed to by stream, obtaining them from the location given by ptr. #include int main() { FILE *fin,*fout; char buffer[11]; if (fin = fopen("fred.txt", "rt")) { fread(buffer, 1, 10, fin); buffer[10] = 0; fclose(fin); fout=fopen("fwrite.txt", "wt"); fwrite (buffer , 1 , sizeof(buffer) , fout ); fclose(fout); } return 0; } d) int main(void) { FILE *fp; char s[80]; int t; if((fp=fopen("test", "w")) == NULL) { printf("Cannot open file. "); exit(1); } printf("Enter a string and a number: "); fscanf(stdin, "%s%d", s, &t); /* read from keyboard */ fprintf(fp, "%s %d", s, t); /* write to file */ fclose(fp); if((fp=fopen("test","r")) == NULL) { printf("Cannot open file. "); exit(1); } fscanf(fp, "%s%d", s, &t); /* read from file */ fprintf(stdout, "%s %d", s, t); /* print on screen */ return 0; } Hope this will help you