用C語言怎麼實現複製自己,c語言實現

來源:互聯網
上載者:User

用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;
}
根據實際需要更改路徑和檔案名稱即可
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.