您的位置:首页 > 运维架构 > Linux

linux实验报告二--文件操作

2006-03-09 10:28 477 查看
//利用底层文件操作函数编写一个mycopy.c程序
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#define maxsize 256 //定义一次从文件读字符的最大数

main(int argc,char *argv[])
{
int fd1,fd2; //定义源文件和目的文件的文件描述符
char buff[maxsize]; //缓冲
int i;
if(argc!=3) //如果命令格式不正确
{ printf("command error!/n");
exit(1);
}
fd1=open(argv[1],O_RDONLY); //以只读的方式打开源文件
if(fd1==-1)
{ printf("file %s cannot open",argv[1]);
exit(1);
}
fd2=open(argv[2],O_WRONLY|O_CREAT|O_APPEND);//以追加的方式创建目的文件
if(fd2==-1)
{ printf("cannot creat file %s",argv[1]);
exit(1);
}
while(1)
{
i=read(fd1,buff,maxsize);
write(fd2,buff,i);
if(i!=maxsize) break; //如果读到的字节数不是希
//望的bufsize,结束文件读写

}
close(fd1);
close(fd2);
}
//使用流文件函数实现相同的功能
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#define maxsize 5

main(int argc,char *argv[])
{
FILE *fp1,*fp2;
char *ch;
if(argc!=3)
{ printf("command error!/n");
exit(1);
}
fp1=fopen(argv[1],"r");
if(fp1==NULL)
{ printf("file %s cannot open",argv[1]);
exit(1);
}
fp2=fopen(argv[2],"wa+");
if(fp2==NULL)
{ printf("cannot creat file %s",argv[1]);
exit(1);
}
while(1)
{
ch=fgets(ch,maxsize,fp1);
if(ch!="EOF")
fputs(ch,fp2);
}

fclose(fp1);
fclose(fp2);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: