WEB开发网
开发学院软件开发Java I/O库函数实现文件复制 阅读

I/O库函数实现文件复制

 2012-06-01 19:27:50 来源:WEB开发网   
核心提示:#include <string.h>//#include <strings.h>#include <stdio.h>#include <stdlib.h>#define BUFFER_SIZE 200long filesize(FILE *stream);int mai
#include <string.h>
//#include <strings.h>
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 200
long filesize(FILE *stream);
int main(int argc,char **argv)
{
	FILE *from_fd;
	FILE *to_fd;
	int read_num,write_num;
	long file_len = 0;
	char buffer[BUFFER_SIZE];
	//char *ptr;

	if(argc != 3)
	{
		fprintf(stderr,"Usage:%s fromfile tofile\n",argv[0]);
		exit(EXIT_FAILURE);
	}
	if((from_fd = fopen(argv[1],"rb")) == NULL)
	{
		fprintf(stderr,"open %s error\n",argv[1]);
		exit(EXIT_FAILURE);
	}
	if((to_fd = fopen(argv[2],"wb")) == NULL)
	{
		fprintf(stderr,"open %s error\n",argv[2]);
		exit(EXIT_FAILURE);
	}
/*
	fseek(from_fd,0L,SEEK_END);
	file_len = ftell(from_fd);
	fseek(from_fd,0L,SEEK_SET);
*/
	file_len = filesize(from_fd);
	printf("from_file size is %ld\n",file_len);
	while(!feof(from_fd))
	{
		if((read_num = fread(buffer,sizeof(char),BUFFER_SIZE,from_fd)) < 0)
		{
			fprintf(stderr,"read error");
			exit(EXIT_FAILURE);
		}
		if(BUFFER_SIZE > file_len)
		{
			if((write_num = fwrite(buffer,sizeof(char),file_len,to_fd)) != file_len)
			{
				fprintf(stderr,"write error");
				exit(EXIT_FAILURE);
			}
		}
		else
		{
			if((write_num = fwrite(buffer,sizeof(char),BUFFER_SIZE,to_fd)) != BUFFER_SIZE)
			{
				fprintf(stderr,"write error");
				exit(EXIT_FAILURE);
			}
			file_len = file_len-BUFFER_SIZE;
		}
		bzero(buffer,BUFFER_SIZE);
	}
	fclose(from_fd);
	fclose(to_fd);
	exit(1);
}

long filesize(FILE *stream)
{
	long curpos,length;
	curpos = ftell(stream);
	fseek(stream,0L,SEEK_END);
	length = ftell(stream);
	fseek(stream,curpos,SEEK_SET);
	return length;
}

点击下载此文件 

Tags:函数 实现 文件

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接