Write a C code that copies one file from the original file to destination file a
ID: 3882917 • Letter: W
Question
Write a C code that copies one file from the original file to destination file as follows.
$ ./copy_HW1 off1 original_file off2 destination_file
1. This usage of command, copy_HW1 shows that copy_HW1 program copies from
(off1+1) th byte to the end of the original_file to destination_file starting from
(off2+1) th byte.
example: $ ./copy_HW1 100 x.txt 50 y.txt : copies contents from 101 st bytes to the
end of x.txt file to 51 st byte position of y.txt
2. The number of command arguments should accept 3 or 4 or 5 arguments.
$ ./copy_HW1 original_file destination_file
copies original_file to destination_file starting from the first position for both files
$ ./copy_HW1 off1 original_file destination_file
copies original_file starting from (off1+1) th byte to destination_file starting from the
first position
$ ./copy_HW1 original_file off2 destination_file
copies original_file starting from the first byte to destination_file starting from the
(off2+1) th byte
Other than this, error message should be returned.
3. Invalid offset value (for example -1 for SEEK_SET) should be checked giving an error
message such as “Invalid argument”.
4. When the specified starting point is greater than the file size of the original_file,
destination_file will have empty content (size 0).
5. Use ‘getLong( ... )’ function defined in tlpi_hdr.h header file
6. Compile using ‘make copy_HW1’ in the ‘fileio’ directory given in the source file
distribution of the textbook.
7. Each case (1 through 5 with different arguments) will be tested.
Explanation / Answer
Here is the C program that copies content from original file to destination file:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
printf("Enter the filename to open for reading ");
scanf("%s", filename);
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s ", filename);
exit(0);
}
printf("Enter the filename to open for writing ");
scanf("%s", filename);
fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s ", filename);
exit(0);
}
c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf(" Contents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.