create a c program using API calls using the following psuedocode Take source fi
ID: 3792495 • Letter: C
Question
create a c program using API calls using the following psuedocode
Take source file name and destination file name from command line
test whether the source file exists // system call
if source file does not exist
display error message based on the error number //using strerror(errno)
exit
else if it is not readable
display error message based on the error number
exit
open the source file for read //system call
if failed to open the source file
display error message based on the error number
exit
test whether the destination file exists // system call
if the destination file exists
prompt user whether to overwrite the destination file
if user enters 0 for no
prompt user whether to append to the destination file
if user enters 0 for no
display a message
exit
else
open the destination for append //system call
else
open the destination for overwrite //system call
else
get the source file status using stat system call //stat() system call
open/create the destination file using the same st_mode as the source file //system call
copy file as shown in cpUnix.c
close both files //close() system call
Explanation / Answer
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <errno.h>
int main(int argc, char const *argv[])
{
int input;
File *fp,*fp1;
int c
if( access( argv[1], F_OK ) != -1 )
{
fp=fopen(argv[1],"r");
if(fp==NULL)
{
printf("Error: %s ", strerror(errno));
exit(0);
}
else
{
if( access( argv[1], F_OK ) != -1 )
{
printf("File exsists , should it be overwritten!Enter your response 1 for yes , 0 for no "); //asking the user whether to over write or not
scanf("%d",&input);
if(input==0)
{
printf("File exsists , should it be appended!Enter your response 1 for yes , 0 for no "); //asking the user whether to over write or not
scanf("%d",&input);
if(input==0)
{
printf("both modes rejected! quiting program...");
struct stat fileStat;
if(stat(argv[1],&fileStat) < 0)
printf("Error: %s ", strerror(errno));
else
{
fp1=fopen(argv[1],fileStat.st_mode); //opening destination file in the mode
if(fp==NULL)
{
printf("Error: %s ", strerror(errno));
}
else
{
seek(fp1, 0L, SEEK_END); // file pointer at end of file
pos = ftell(fp1);
fseek(fp1, 0L, SEEK_SET); // file pointer set at start
while (pos--)
{
ch = fgetc(fp1); // copying file character by character
fputc(ch, fp2);
}
fclose(fp);
fclose(fp1);
}
}
exit(0);
}
else
{
fp1=fopen(argv[2],"a") ; // opening file in append mode
}
}
else
{
fp1=fopen(argv[2],"w"); // opening file by overwritting the exsisitng file
}
}
else
{
printf("Error: %s ", strerror(errno));
exit(0);
}
}
}
else
{
printf("Error: %s ", strerror(errno));
exit(0);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.