Clone or Copy File in C
Generally there was someone in one of the forums i am on was asking how to duplicate a file. So basically this little post i made up was to help this guy. There are fundamentally few ways so i will write them up in code tags below.
Option 1: Using the FILE * handle with fgetc
[code]
/*
* This source code was written by GenesisDatabase
* Visit http://genesisdatabase.wordpress.com for more source codes
*
* Date of release: 1st February 2011
*/
#include <stdio.h>
#define FILENAME_ORI "ori.exe"
#define FILENAME_NEW "new.exe"
int main()
{
FILE *r = NULL;
FILE *w = NULL;
char c = '\0';
// open handle for reading
r = fopen(FILENAME_ORI, "rb");
if(r == NULL)
{
printf("Error: fopen\n");
return -1;
}
// open handle for writing
w = fopen(FILENAME_NEW, "wb");
if(w == NULL)
{
printf("Error: fopen\n");
fclose(r);
return -2;
}
while(1)
{
// read offset byte
c = fgetc(r);
// if it reached EOF
if(c == EOF)
break;
// write offset byte
fputc(c, w);
}
// close handle
fclose(r);
fclose(w);
printf("Success\n");
return 0;
}
[/code]
Option 2: Using the FILE * handle with fread
[code]
/*
* This source code was written by GenesisDatabase
* Visit http://genesisdatabase.wordpress.com for more source codes
*
* Date of release: 1st February 2011
*/
#include <stdio.h>
#include <memory.h>
#include <malloc.h>
#define FILENAME_ORI "ori.exe"
#define FILENAME_NEW "new.exe"
int main()
{
FILE *r = NULL;
FILE *w = NULL;
char *buf = NULL;
unsigned int size = 0;
// open handle for reading
r = fopen(FILENAME_ORI, "rb");
if(r == NULL)
{
printf("Error: fopen\n");
return -1;
}
// open handle for writing
w = fopen(FILENAME_NEW, "wb");
if(w == NULL)
{
printf("Error: fopen\n");
fclose(r);
return -2;
}
fseek(r, 0, SEEK_END);
size = ftell(r);
rewind(r);
// allocate memory for buffer
buf = (char *)malloc(size);
memset(buf, 0, size);
// read bytes into buffer
fread(buf, 1, size, r);
// write bytes into file
fwrite(buf, 1, size, w);
// close handle
fclose(r);
fclose(w);
printf("Success\n");
return 0;
}
[/code]
Option 3: Using the CopyFile API
[code]
/*
* This source code was written by GenesisDatabase
* Visit http://genesisdatabase.wordpress.com for more source codes
*
* Date of release: 1st February 2011
*/
#include <stdio.h>
#define FILENAME_ORI "ori.exe"
#define FILENAME_NEW "new.exe"
int main()
{
// argv 1 = source file
// argv 2 = destination file
// argv 3 = if destination files exists, FALSE overwrites the existing file,
// TRUE returns fail
if(CopyFile(FILENAME_ORI, FILENAME_NEW, FALSE) == 0)
{
printf("Error: CopyFile\n");
return 1;
}
printf("Success\n");
return 0;
}
[/code]
You can find out how to use the functions in the links below.
1.) CopyFile
2.) fgetc
3.) fputc
4.) fread
5.) fwrite
And some ways you could use to delete files or move files.
1.) DeleteFile
2.) MoveFile
3.) rename
4.) unlink
Currently have 0 comments: