llinux文件编程2

来源:互联网 发布:unity3d awake 编辑:程序博客网 时间:2024/05/18 16:39

本文通过一个拷贝文件的程序介绍下,linux访问系统库函数open close read write四个函数

1.先把完整程序贴上,在一步一步介绍程序流程。

#include <stdio.h>
#include <stdlib.h>


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


#define size 1000
int bytes_read,bytes_write;
char buf[size];
int main(int argc,char *argv[])
{
   int fd1,fd2;
   char *p;
   if(argc!=3)
   {
     printf("input format mistake: only and but only two file name \n");
     exit(1);

   }
   if((fd1=open(argv[1],O_RDONLY))<0)
   {
      printf("open file1 failed!\n");
      exit(1);
   }

  if((fd2=open(argv[2],O_WRONLY|O_CREAT,0755))<0)
   {
      printf("open file2 failed!\n");
      exit(1);
   }
   while(bytes_read=read(fd1,buf,size))
   {
      if(bytes_read<0)
          break;
      else if(bytes_read>0)
      {
         p=buf;
         while(bytes_write=write(fd2,p,bytes_read))
         {
           if((bytes_write<0)||(bytes_write==bytes_read))
              break;
           else if((bytes_write>0)&&(bytes_write!=bytes_read))
           {
              p+=bytes_write;
              bytes_read=bytes_read-bytes_write;
           }
         }
      }
   }
   close(fd1);
   close(fd2);
}


2:程序分析

2.1 首先进行参数检查,总共三个参数,两个文件,把一个文件的数据的一部分拷贝到另一个文件中

 if(argc!=3)
   {
     printf("input format mistake: only and but only two file name \n");
     exit(1);

   }

2.2 建立总体框架

   打开两个文件,一个文件只读就可以了,另一个设置为可写,当不存在时,必须要创建,同时可以先把关闭文件

   的函数先写了。

   

 if((fd1=open(argv[1],O_RDONLY))<0)
   {
      printf("open file1 failed!\n");
      exit(1);
   }

  if((fd2=open(argv[2],O_WRONLY|O_CREAT,0755))<0)
   {
      printf("open file2 failed!\n");
      exit(1);
   }

  .....

  close(fd1);
  close(fd2);

3.打开文件成功后,开始进入拷贝文件过程

  1.bytes_read=read(fd1,buf,size);读取size个字节,实际读到多少,返回为bytes_read

  2.此时继续进行判断,当返回值bytes_read<0,代表没有读到东西,直接退出循坏,此时没有必要拷贝

  若读到内容,则开始把读出来的内容放到另一个文件中。

 3.else if(bytes_read>0)
      {
         p=buf;
         while(bytes_write=write(fd2,p,bytes_read))
         {
           if((bytes_write<0)||(bytes_write==bytes_read))
              break;
           else if((bytes_write>0)&&(bytes_write!=bytes_read))
           {
              p+=bytes_write;
              bytes_read=bytes_read-bytes_write;
           }

       }

这里为什么要设置一个指针指向buf数组,为什么还要用while循环呢?

因为:bytes_write=write(fd2,p,bytes_read) 调用这个函数时,虽然要求写入bytes_read个字节

          但实际的情况可能一次性不能写入这么多字节,因此通过返回值bytes_write就可以知道究竟写入多少字节

          当bytes_write<0直接退出,写入失败,或bytes_write=bytes_read 写入成功,也退出。

          (bytes_write>0)&&(bytes_write!=bytes_read)一次性没写完,继续把剩余的写完。

         

原创粉丝点击