234k views
0 votes
Write a C program (doublecopy) that allows a user to extract some part of an existing file (fileSource) and copy it twice to a new file fileTarget. The user can specify (1) the number of bytes (num1) as an offset from the beginning of filesource, (2) how many bytes (num2) that will be extracted from it, and ,(3) the new fileTarget name. >doublecopy num1 num2 filesource fileTarget

User MilanG
by
6.3k points

1 Answer

2 votes

Answer:

Check the explanation

Step-by-step explanation:

#include <stdio.h>

#include <sys/stat.h>

#include <stdlib.h>

#include <fcntl.h>

#include <errno.h>

#include <unistd.h>

extern int errno;

struct stat st;

int main(int argc, char **argv){

int num1 = atoi(argv[1]); // Getting num1 from user

int num2 = atoi(argv[2]); // Getting num2 from user

char *fileSource = argv[3];

char *fileTarget = argv[4];

int source_fd = open(fileSource, O_RDONLY); // opening the file in read only mode

int target_fd = open(fileTarget, O_WRONLY | O_CREAT); // opening the target file in Writeonly mode if file is not found it will create

char *ch = (char *) calloc(num2+num1, sizeof(char));

stat(fileSource, &st);

if(st.st_size < (num1 + num2)){

printf("File Size is smaller than the specified bytes\\");

read(source_fd, ch, st.st_size); // reading the file upto the end

write(target_fd, ch, st.st_size); // write to the file

write(target_fd, ch, st.st_size); // two times writing to the file

}else{

if(lseek(source_fd, (off_t)num1, SEEK_SET) < 0 ) // moving the cursor to after the specified bytes from the start

{

printf("Some Error occured while seeking the file");

return -1;

}

read(source_fd, ch, num2); // reading num2 bytes from the source

write(target_fd, ch, num2); // writing two times to the target

write(target_fd, ch, num2);

}

return 0;

}

1 2 #include <stdio.h> #include <sys/stat.h> #include <stdlib.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> 4

The code screenshot and code output are attached below.

Write a C program (doublecopy) that allows a user to extract some part of an existing-example-1
Write a C program (doublecopy) that allows a user to extract some part of an existing-example-2
Write a C program (doublecopy) that allows a user to extract some part of an existing-example-3
User Svetoslav Petkov
by
6.7k points