/*Using system call implementation file copy function:
Manual input source file target file pathname pathname
If the destination does not exist, create and write*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
/*Handle source file*/
char* source_file(const char* pathname)
{
size_t length;
int fd;
char* buf = NULL;
if(access(pathname,F_OK) == -1)
{
perror("Error! The source file doesn't exist");
exit(1);
}
if((fd=open(pathname,O_RDWR)) < 0)
{
printf("Open %s failure!/n",pathname);
exit(1);
}
length = lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
buf = (char*)malloc(length*(sizeof(char)));
read(fd, buf, length);
printf("%s",buf);
close(fd);
return buf;
}
/*Handle object file*/
void object_file(const char* pathname, char* source_buf)
{
int fd;
if((fd=open(pathname, O_CREAT|O_RDWR, 0777)) < 0)
{
printf("Open %s failure!/n",pathname);
exit(1);
}
write(fd, source_buf, (strlen(source_buf)+1));
close(fd);
}
/*The main function*/
int main(int argc, char* argv[])
{
char* source_path = (char*)malloc(30*(sizeof(char)));
char* object_path = (char*)malloc(30*(sizeof(char)));
char* source_buf = NULL;
puts("Please input the source file pathname:");
scanf("%s",source_path);
puts("Please input the object file pathname:");
scanf("%s",object_path);
source_buf = source_file(source_path);
object_file(object_path, source_buf);
free(source_path);
free(object_path);
free(source_buf);
return 0;
}