胡神

导航

2-3 几种文件复制方法-文件访问

(1)文件复制----单字符

#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>

int main()
{
char c;
int in,out;

in=open("read1.c", O_RDONLY);
out=open("write1.c",O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR);

while(read(in,&c,1)==1)
write(out,&c,1);

close(in);
close(out);

exit(0);
}

(2)文件复制----字符串

#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>

int main()
{
char block[1024];
int in,out;
int nread;

in=open("read1.c", O_RDONLY);
out=open("write2.c",O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR);

while((nread=read(in,block,sizeof(block)))>0)
write(out,block,nread);

close(in);
close(out);

exit(0);
}

 

(3)文件复制----单字符

 

#include <stdio.h>
main()
{
FILE *in,*out;
char ch;
if((in=fopen("s2","rt"))==NULL)
{
printf("存在错误\n");
//getch();
exit(1);
}

if((out=fopen("s3","a+"))==NULL)
{
printf("存在错误\n");
//getch();
exit(1);
}

ch=fgetc(in);
while(ch!=EOF)
{
putchar(ch); ///////////////
fputc(ch,out);
ch=fgetc(in);

}
fclose(in);
fclose(out);
}

 

 

(4)文件复制----字符串

 

 

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>

#define BUFFER_SIZE 1024

int main(int argc,char **argv)
{
int from_fd,to_fd;
int bytes_read,bytes_write;
char buffer[BUFFER_SIZE];
char *ptr;

if(argc!=3)
{
fprintf(stderr,"Usage:%s from file to file\n",argv[0]);
exit(1);
}

/*打开源文件*/
if((from_fd=open(argv[1],O_RDONLY))==-1)
{
fprintf(stderr,"open %s Error:%s\n",argv[1],strerror(errno));
exit(1);
}

/*创建目的文件*/
if((to_fd=open(argv[2],O_WRONLY | O_CREAT,S_IRUSR | S_IWUSR))==-1)
{
fprintf(stderr,"open %s Error:%s\n",argv[2],strerror(errno));
exit(1);
}

/*以下代码是一个经典的拷贝文件的代码*/
while(bytes_read=read(from_fd,buffer,BUFFER_SIZE))
{
/*一个致命的错误发生里*/
if((bytes_read==-1)&&(errno!=EINTR))
break;
else if(bytes_read>0)
{
ptr=buffer;
while(bytes_write=write(to_fd,ptr,bytes_read))
{
/*一个致命的错误发生里*/
if((bytes_write==-1)&&(errno!=EINTR))
break;
/*写完里所有的字节*/
else if(bytes_write==bytes_read)
break;
/*只写完一部分继续写*/
else if(bytes_write>0)
{
ptr+=bytes_write;
bytes_read-=bytes_write;
}

}
if(bytes_write==-1)
break;
}
}
close(from_fd);
close(to_fd);
exit(0);
}


5.方法同上


#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>

int main()
{
        char block[1024];
        int in,out;
        int nread;

        in=open("s1",O_RDONLY);
        out=open("s5",O_WRONLY | O_CREAT,S_IRUSR | S_IWUSR);

        while((nread=read(in,block,sizeof(block)))>0)
                write(out,block,nread);

        exit(0);
}

 

posted on 2011-08-26 23:52  胡神  阅读(1009)  评论(0编辑  收藏  举报