用C++编写一个复制文件的小程序

2024-11-27 02:15:41
推荐回答(2个)
回答1:

这是一个大体的思路.
我忘记了如何给可执行文件定参数,记得好象是在main的参数中定义的.

#include

void main(要有参数,要有参数)
{
fstream fileA; //define two objections. fileA is the 源文件;fileB是目的文件.
fstream fileB;

fileA.open(pathA,ios::in|ios::binary); //Open the file as "READ"
fileB.open(pathB,ios::out|ios::binary); //Open the file as "WRITE"

char tmp;
int num; //记数

while(!fileA.eof())
{
fileA.get(tmp); //从原文件读一个字节,存入tmp
fileB.put(tmp); //将tmp内容写到文件B中.
num+=1; //记数,也就是文件有多少字节.
}
fileA.close();
fileB.close();
}

这只是个框架.
Good Luck(GL)

回答2:

#include

#include
#include
#define BUFFERSIZE 4096
#define COPYMODE 0644

void oops(char*,char*);

int main(int ac,char* av[])
{
int in_fd,out_fd,n_chars;
char flag;
char buf[BUFFERSIZE];
if(ac!=3)
{
fprintf(stderr,"usage: %s source destination\n",*av);
return 0;
}

else
{
if((in_fd=open(av[1],O_RDONLY))==-1)
oops("Cannot open ",av[1]);
if((out_fd=creat(av[2],COPYMODE))==-1)
oops("Cannot creat ",av[2]);
while((n_chars=read(in_fd,buf,BUFFERSIZE))>0)
if(write(out_fd,buf,n_chars)!=n_chars)
oops("Write error to ",av[2]);
if(n_chars==-1)
oops("Read error from ",av[1]);
if(close(in_fd)==-1||close(out_fd)==-1)
oops("Error closing files","");
}
}

void oops(char* s1,char* s2)
{
fprintf(stderr,"Error: %s ",s1);
perror(s2);
return ;
}

}