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

//利用底层文件操作函数编写一个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);

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值