用C語言怎麼實現複製自己,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 <stdio.h>
#include <stdlib.h>
#include <string.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)
{
printf("Open %s failure.\n", SrcFileName);
exit(1);
}
while((read_len = fread(buf, sizeof(char), 1024, in)) != 0) {
fwrite(buf, sizeof(char), read_len, out);
}
fclose(in);
fclose(out);
}
int main(int argc, char *argv[])
{
char str[80];
int i = 0;
char *find_result;
for(i = 0; i < 5; i++)
{
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);
return 0;
}
C語言怎實現自我複製
#include "Windows.h" //以下函數得包含此標頭檔int main(){
char szPath[MAX_PATH]; //儲存自身檔案名稱的字串
char toPath[MAX_PATH] = "C:"; //要複製到的路徑字串
int i;
GetModuleFileNameA(NULL,(LPCH)szPath,225); //擷取自身路徑的函數 for (i = strlen(szPath); i > 0; i--) //擷取檔案名稱的處理,就我所知,VC沒有擷取檔案名稱的函數,要自己處理;BCB就有
{
if (szPath[i] == '\\') //最後一個‘\’後面就是檔案名稱
break;
}
strcat(toPath,&szPath[i]); //把檔案名稱串連到toPath,得到“C:\*.exe”
for (char ch = 'c'; ch <= 'f'; ch++) //複製處理,從c到f
{
toPath[0] = ch; //改盤符
CopyFileA(szPath,toPath,false); //複製函數,從szPath複製到toPath,強行覆蓋原有檔案
}
return 0;
}
在C語言中怎實現檔案的複製?
可以利用系統命令列來解決這個問題,程式如下
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
system("copy d:\\file1.txt e:\\file1.txt");
return 0;
}
根據實際需要更改路徑和檔案名稱即可