CopyFile

拷贝一般文件

main(int arg, char *args[]) {

if (arg < 3)

return -1;

const char *srcFile = args[1];

const char *desFile = args[2];

FILE *psrc = fopen(srcFile, "r"); //用只读方式读取源文件

if (psrc == NULL) {

printf("%s:%s open failed\n", srcFile, strerror(errno));

return -1;

}

FILE *pdesc = fopen(desFile, "w"); //用只读方式读取源文件

if (psrc == NULL) {

printf("%s:%s open failed\n", desFile, strerror(errno));

return -1;

}

struct stat st;

memset(&st, 0, sizeof(st));

if (stat(srcFile, &st) == -1) {

printf("stat failed");

return -1;

}

char *buf = malloc(st.st_size); //根据源文件的实际大小,动态分配一块内存空间

size_t rc = fread(buf, 1, st.st_size, psrc);

fwrite(buf, 1, rc, pdesc); //源文件内容写入

fclose(psrc);

fclose(pdesc);

free(buf);

return 0;

}


拷贝大文件

int main(int arg, char *args[]) {

if (arg < 3)

return -1;

const char *srcFile = args[1];

const char *desFile = args[2];

FILE *psrc = fopen(srcFile, "r"); //用只读方式读取源文件

if (psrc == NULL) {

printf("%s:%s open failed\n", srcFile, strerror(errno));

return -1;

}

FILE *pdesc = fopen(desFile, "w"); //用只读方式读取源文件

if (psrc == NULL) {

printf("%s:%s open failed\n", desFile, strerror(errno));

return -1;

}

struct stat st;

memset(&st, 0, sizeof(st));

if (stat(srcFile, &st) == -1) {

printf("stat failed");

return -1;

}

char buf[1024]

//根据源文件的实际大小,动态分配一块内存空间

while (1) {

size_t rc = fread(buf, 1, sizeof(buf), psrc);

if (rc <= 0) {

break;

}

fwrite(buf, 1, rc, pdesc);

}

fwrite(buf, 1, rc, pdesc); //源文件内容写入

fclose(psrc);

fclose(pdesc);

free(buf);

return 0;

}

你可能感兴趣的:(CopyFile)