gramming Problems 2.26 In Section 2.3, we described a program that copies the co
ID: 3872178 • Letter: G
Question
gramming Problems 2.26 In Section 2.3, we described a program that copies the contents of one file to a destination file. This program works by first prompting the user for the name of the source and destination files. Write this program using either the Windows or POSIX API. Be sure to include all necessary error checking, including ensuring that the source file exists Once you have correctly designed and tested the program, if you used a system that supports it, run the program using a utility that traces system calls. Linux systems provide the strace utility, and Solaris and Mac OS X systems use the dtrace command. As Windows systems do not provide such features, you will have to trace through the Windows version of this program using a debuggerExplanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char* argv[]) {
//Assuming "input.txt" is the source file
//and, "output.txt" is the destination file
char* inputFile = "input.txt";
char* outputFile = "output.txt";
//inputFileDesc : input File descriptor
//outputFileDesc : output File descriptor
int inputFileDesc, outputFileDesc;
//to store bytes read and written from/to file respectively
ssize_t bytesRead, bytesWritten;
//buffersize 2^15
int bufferSize = 32768;
char buffer[bufferSize];
inputFileDesc = open (inputFile, O_RDONLY);
if (inputFileDesc == -1) {
perror ("Error while opening Input File");
return 2;
}
//open output file
outputFileDesc = open(argv[2], O_WRONLY | O_CREAT, 0644);
if(outputFileDesc == -1){
perror("Error while opening Output File");
return 3;
}
//read input file
while((bytesRead = read (inputFileDesc, &buffer, bufferSize)) > 0){
bytesWritten = write (outputFileDesc, &buffer, (ssize_t) bytesRead);
if(bytesWritten != bytesRead){
perror("Error while writing");
return 4;
}
}
//close input and output file
close (inputFileDesc);
close (outputFileDesc);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.