天天看點

用C語言怎麼實作複制自己

#include <stdio.h>

#include <string.h>

int main(int argc, char *argv[])

{

char str[80];

int i = 0;

for(i = 0; i < 5; i++)

sprintf(str, "cp %s %d%s", argv[0], i, ".out");  //在WIN下用copy取代cp

system(str);

}

//printf("%s\n", str);

return 0;

下邊是自己動手寫的copy函數

#include <stdlib.h>

void copy_file(char *SrcFileName, char *DesFileName)

char buf[1024];

int read_len = 0;

FILE *in = NULL;

FILE *out = NULL;

if((in = fopen(SrcFileName, "rb")) == NULL)

printf("Open %s failure.\n", SrcFileName);

exit(1);

if((out = fopen(DesFileName, "wb")) == NULL)

while((read_len = fread(buf, sizeof(char), 1024, in)) != 0) {

fwrite(buf, sizeof(char), read_len, out);

fclose(in);

fclose(out);

char *find_result;

sprintf(str, "%d%s", i, ".out");

find_result = strrchr(argv[0], '/');

if (strcmp(str, find_result + 1) !=0 )

copy_file(argv[0], str);

printf("%s\n", str);