#include <stdio.h>
#include <stdlib.h>
int filecopy(char* input_name,char* output_name)
{
FILE *input, *output;
unsigned char current_byte;
input = fopen(input_name, "rb");
output = fopen(output_name, "wb");
if(input==NULL || output==NULL)
{
return -1;
}
while(1)
{
fread(¤t_byte, sizeof(unsigned char), 1, input);
if(feof(input))
{
break;
}
fwrite(¤t_byte, sizeof(unsigned char), 1, output);
}
fflush(input);
fflush(output);
fclose(input);
fclose(output);
return 0;
}
//https://github.com/atamenne/file-copy/blob/master/filecopy.c
//Simple program to copy a file
int main(int argc,char* argv[])
{
char input_name[30], output_name[30];
if(argc>1)
{
strcpy(input_name,argv[1]);
}else{
printf("enter input_name:");
scanf("%s", &input_name);
}
if(argc>2)
{
strcpy(output_name,argv[2]);
}else{
printf("Enter output_name:");
scanf("%s", &output_name);
}
printf("argc=%d input_name=%s output_name=%s\n",argc,input_name,output_name);
filecopy(input_name,output_name);
return 0;
}
/*
* copy_file.c
*
* A simple C program for copying text files and observing system calls.
*
* Bradley Taniguchi: First draft, program structure, prompt()
* Matt Levan: Function/variable naming cleanup, copy(), file_exists()
* 02/01/16 -- Spring 2016
* Project 1
* CSC-341 Operating Systems
* Dr. Bin Tang
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define __WIN32__ 1
#if(defined(__WIN32__))
#include <io.h>
#include <process.h>
#else
#include <unistd.h>
#endif
bool file_exists(char *file_name) {
FILE *file_ptr = fopen(file_name, "r");
if (!file_ptr) {
return false;
}
return true;
}
void copy(char *out_str, char *in_str) {
// int c to store one char at a time
int c;
// declare and open files for copy
FILE *in_ptr = fopen(in_str, "r");
FILE *out_ptr = fopen(out_str, "w");
if (!in_ptr) {
perror("Source file can't be opened: ");
exit(1);
}
if (!out_ptr) {
perror("Destination file can't be opened: ");
exit(1);
}
// copy file one char at a time
while ((c = fgetc(in_ptr)) != EOF) {
fputc(c, out_ptr);
}
// success
printf("\nSuccess!\n");
// close files
fclose(in_ptr);
fclose(out_ptr);
}
void prompt_user() { // primary function to be ran, asks user for inputs
char str[32], in_str[32], out_str[32]; // 32 char width is fine
char *str_ptr = str;
char *in_ptr = in_str;
char *out_ptr = out_str;
// get name of source file
while (strcmp(in_str, "")) { // while in_str is empty
printf("Enter name of source file: ");
scanf("%s", str_ptr); // get input from keyboard (stdin)
if (file_exists(str_ptr)) {
strcpy(in_str, str);
break;
}
else {
printf("File can't be opened!\n");
continue;
}
}
// get name of destination file
while (strcmp(out_str, "")) { // while out_str is empty
printf("Enter name of destination file: ");
scanf("%s", str_ptr); // get input from keyboard (stdin)
if (!file_exists(str_ptr)) {
strcpy(out_str, str);
break;
}
else {
printf("File already exists!\n");
continue;
}
}
copy(out_str, in_str);
}
int main() {
prompt_user();
return EXIT_SUCCESS;
}
源码下载: