编写一个程序,用系统/标准IO提供的函数接口,实现文件的拷贝

更多资料请点击:我的目录
本篇仅用于记录自己所学知识及应用,代码仍可优化,仅供参考,如果发现有错误的地方,尽管留言于我,谢谢。

做法1 :系统IO:

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char **argv)
{	
	//检验输入参数是否有三位
	if(argc != 3)
	{
		perror("输入错误!\n");
		exit(0);
	}

	//系统IO打开一个指定文件并获得文件描述符(成功返回大于等于0的整数),或创建一个新文件
	int src = open(argv[1], O_RDONLY);	//argv[1]为用户输入参数所指的文件,O_RDONLY(以只读方式打开文件)
	if ( src == -1 )			//失败返回-1
	{
		perror("打开源文件失败!\n");
		exit(0);
	}

	int dst = open(argv[2],O_WRONLY|O_CREAT|O_TRUNC,0644);	//argv[2]为用户输入参数所指的文件,
	if( dst == -1 )											//O_WRONLY(以只写方式打开文件)、
	{														//O_CREAT(如文件不存在则创建)、
		perror("打开目标文件失败!\n");						//O_TRUNC(如文件存在则清空原有数据)
		exit(0);											//0644 (为创建文件时制定其权限)
	}

	//创建一块占100字节的内存
	char *buf = calloc(1,100);				
	
	while(1)
	{
		//系统IO从指定文件中读取数据,返回实际读到的字节数
		int n = read(src, buf, 100);	
		if( n == 0 )
		{
			printf("复制完成!\n");
			break;
		}
		if( n == -1 )//读取失败返回-1
		{
			printf("读取错误!\n");
			break;
		}
		char *tmp = buf;
		if( n > 0 )
		{
			//系统IO将数据写入指定的文件
			int m = write(dst, tmp, n);
			n -= m;
			tmp += m; 
		}
	}	
	close(src);//系统IO关闭文件并释放相应的资源
	close(dst);
	free(buf);//释放内存
	return 0;
}

做法2 :标准IO:

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

int main(int argc, char **argv)
{
	//判断输入参数是否正确
	if(argc != 3)
	{
		perror("输入错误!\n");
		exit(0);
	}

	//标准IO获取指定文件的文件指针,r(以只读方式打开文件,要求文件必须存在)
	FILE * src = fopen (argv[1],"r");
	if(src == NULL)		//打开失败返回NULL
	{
		perror("打开源文件失败!\n");
		exit(0);
	}

	//w(以只写方式打开文件,如文件不存在则创建,如文件存在则清空原有数据)
	FILE * dst = fopen (argv[2],"w");
	if(dst == NULL)		//打开失败返回NULL
	{
		perror("打开目标文件失败!\n");
		exit(0);
	}

	//创建五块占20字节的内存
	char *buf = calloc(5,20);
	long a,b;
	
	while(1)
	{	
		//ftell()获取指定文件的当前位置偏移量
		a = ftell(src);
		
		//fread()从指定文件读取若干个数据块
		int n = fread(buf, 20, 5, src);
		if(n == 5)
		{
			//fwrite()将若干块数据写入指定的文件
			if(fwrite(buf, 20, n, dst) !=n)
			{
				perror("写入目标文件失败!\n");
				break;
			}
		}
		else
		{
			if(feof(src)) //feof()判断一个文件是否到达文件末尾
			{		
				b = ftell(src);
				if(fwrite(buf, b-a, 1, dst) != 1)
				{
					perror("写入目标文件失败\n");
					break;
				} 
				printf("文件拷贝成功!\n");
				break;
			}
			if(ferror(src))
			{
				perror("写入目标文件失败!\n");
				break;
			}
		}		
	}
	fclose(src);//标准IO关闭文件并释放相应的资源
	fclose(dst);
	free(buf);//释放内存
	return 0;
}

更多资料请点击:我的目录

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章