Hi I\'m doing a C programming assignment on Ubuntu server. The goal is to write
ID: 3704166 • Letter: H
Question
Hi I'm doing a C programming assignment on Ubuntu server. The goal is to write a program that copies the contents of a file exactly.
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int error(char* msg)
{
perror(msg);
return 2;
}
int usage(char* name)
{
printf("Usage: %s <file to copy> <name of copy> ", name);
return 1;
}
int main(int argc, char* argv[])
{
if (argc != 3)
return usage(argv[0]);
// open files
// read bytes from original file and
// write to copy
FILE *fr = fopen(argv[1], "r");
if(!fr) {
error("file to copy does not exists");
} else {
FILE *temp = fopen(argv[2], "r");
if(temp) {
error("name of copy already exists");
} else {
fclose(temp);
FILE *fw = fopen(argv[2], "w");
if(fw) {
char ch = 0;
while((ch = getc(fr)) != EOF) {
putc(ch, fw);
}
fclose(fw);
} else {
error("can not write to name of copy");
}
}
fclose(fr);
}
// close files
return 0;
}
Explanation / Answer
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int error(char* msg)
{
perror(msg);
return 2;
}
int usage(char* name)
{
printf("Usage: %s <file to copy> <name of copy> ", name);
return 1;
}
int main(int argc, char* argv[])
{
if (argc != 3)
return usage(argv[0]);
// open files
// read bytes from original file and
// write to copy
FILE *fr = fopen(argv[1], "r");
if(!fr) {
error("file to copy does not exists");
} else {
FILE *temp = fopen(argv[2], "r");
if(temp) {
error("name of copy already exists");
} else {
//chegEA , commented below line which gives segmentation fault if file to cpy doent exists and try to close
//fclose(temp);
FILE *fw = fopen(argv[2], "w");
if(fw) {
char ch = 0;
while((ch = getc(fr)) != EOF) {
putc(ch, fw);
}
fclose(fw);
} else {
error("can not write to name of copy");
}
}
//Chegg EA, chek if fr is not null , then close it,otherwise it gives segmentation fault
if(!fr)
fclose(fr);
}
// close files
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.