I have trouble searching for a solution on how to send a successfully, copied file to a chosen destination and/or directory in C, instead of copying a file into the same destination. How do you do that? what should I do to fix this problem?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char *file[])
{
int ch; //ch - character no.
struct stat sb;
FILE *source, *target;
/* from http://stackoverflow.com/questions/30215462/how-to-get-the-source- files-the-file-which-i-want-to-copy-and-the-copied-file/30217023#30217023 */
if (argc <= 2) {
printf("Enter source and destination file names\n");
exit(EXIT_FAILURE);
}
if ( strcmp(file[1], file[2]) ==0 )
{
printf("the files are the same\n");
exit(1);
}
/* if ( file[2] != NULL)
{
printf("the destination file exists\n");
exit(1);
}*/
source = fopen(file[1], "r");//getting and opening source file
if( source == NULL ) {
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
target = fopen(file[2], "w");//getting and opening destination file
if( target == NULL ) {
fclose(source);
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
while( ( ch = fgetc(source) ) != EOF )
fputc(ch, target);
fclose(source);
fclose(target);
printf("File copied successfully.\n");
/* from http://stackoverflow.com/questions/30215462/how-to-get-the-source-files-the-file-which-i-want-to-copy-and-the-copied-file/30217023#30217023 */
if (stat(file[1], &sb) == -1) {
perror("stat");
exit(1); //exit(EXIT_SUCCESS);
}
else
if (chmod(file[2], sb.st_mode & 07777))//http://stackoverflow.com/questions/18032574/how-can-i-copy-permissions-from-a-file-that-already-exists
{
perror("chmod");
}
printf("Source File: %s, Inode number: %d, Mode: 0x%04X\n", file[1], (unsigned)sb.st_ino, (unsigned)sb.st_mode);
if (stat(file[2], &sb) == -1) {
perror("stat");
exit(1);
}
char *str;
str = (char *) malloc(15);
strcpy(str, file[2]);
if (stat(file[2], &sb) == -1) {//http://stackoverflow.com/questions/7430248/creating-a-new-directory-in-c
mkdir(file[2], 0700);
}
printf("Destination File: %s, inode number: %d, Address = %u, Mode: 0x%04X\n", file[2], (unsigned)sb.st_ino, str, (unsigned)sb.st_mode);
free(str);
return 0;
}