学习文件操作之一

#include  <stdio.h>
  2 #include  <fcntl.h>
  3 #include  <unistd.h>
  4 #define     MAXSIZE  50 
  5 char buf1[MAXSIZE] =  "sadfljlkj;jjjlkj;aj";
  6 char buf2[MAXSIZE];
  7 int main(int argc, char *argv[])
  8 {
  9         int fd;
 10         /*if((fd = open("test.c", O_RDWR | O_CREAT | O_APPEND, S_IRWXU)) < 0    ); */
 11         if((fd = creat("test2",S_IRWXU ))  < 0)
 12          printf("the file is not opened!\n");
 13         if(write(fd ,buf1,sizeof(buf1)) != sizeof(buf1) )
 14                 printf("write wrong!\n");
 15         close(fd);
 16         if((fd =open("test2",O_RDONLY)) < 0)
 17          printf("the file is not opened!\n");
 18         /*      if(lseek(fd,0,0) == -1)
 19                 printf("cannot seek\n");
 20         */
 21         if(read(fd,buf2,10) != 10)
 22                 printf("read wrong!\n");
            printf("%s\n",buf2);
 24         close(fd); 
 25   }


非常蹩脚的程序,一步一步来吧

(1)write完后直接read,犯了文件偏移量的错误,因为write后偏移量到了文件末尾,自然是读不出来的,需要lseek,但是我试过了lseek,还是read不出来,看被注释的代码

(2) open 不对,我尝试 直接open一个已存在的文件,如果不存在就创建,存在就在文件末尾添加数据,但是失败了。



继续学习,把一个文件拷贝给另外一个文件 ,小技巧是while,数目可以随意,如果到了末尾就会返回零,退出循环


  1 #include  <stdio.h>
  2 #include  <fcntl.h>
  3 #include  <unistd.h>
  4 int main(int argc, char *argv[])
  5 {
  6         int fd1, fd2;
  7         char *buf;
  8         size_t num;
  9         if((fd1 = open(argv[1],O_RDONLY,S_IRWXU)) < 0)
 10                         printf("open wrong! \n");
 11         if( (fd2 = open(argv[2],O_WRONLY | O_CREAT, S_IRWXU )) < 0)
 12                 printf("open wrong too !\n");
 13         while(num = read(fd1, buf, 20))
 14                 write(fd2, buf, 20);
 15         close(fd1);
 16         close(fd2);
 17 
 18 }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值