Chinaunix首页 | 论坛 | 博客
  • 博客访问: 27336
  • 博文数量: 10
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 75
  • 用 户 组: 普通用户
  • 注册时间: 2014-10-20 12:05
个人简介

.

文章分类
文章存档

2015年(1)

2014年(9)

我的朋友

分类: LINUX

2014-11-05 23:29:50

今天在图书馆看了国嵌 linux应用编程 利用系统调用对文件进行操作,总结一下自己认为重要的几点。
1.打开文件(可以用来创建文件)int open(int*filename,RDONLY|WRONLY|RDWR),如果要打开一个不存在的文件,相当于创建一个文件,则需要添加一个文件权限的参数(如:0777)。~chmod
2.读取文件中的信息 以及向文件中写入信息。int read(int*filename,buffer,size),表述比较简略,基本意思是从filename中读取size大小的文件 到buffer中,返回值为读出的文件大小;int write(int*filename,buffer,size),表示从buffer中 提取size大小的字节写到filename中。
下面程序是实现copy功能,其中有点小地方不懂,太晚了明天搞。

点击(此处)折叠或打开

  1. #include<sys/types.h>
  2. #include<sys/stat.h>
  3. #include<fcntl.h>
  4. #include<stdio.h>
  5. #include<errno.h>
  6.  
  7. #define BUFFER_SIZE 1024

  8. int main(int argc,char **argv)
  9. {
  10.     int from_fd,to_fd,bytes_read,bytes_write;
  11.     char buffer[BUFFER_SIZE];
  12.     char *ptr;
  13.     if(argc!=3){
  14.     printf("the function of file_cp need two files\n");
  15.     exit(1);
  16.     }
  17. if((from_fd=open(argv[1],O_RDONLY))==-1
  18. {
  19.     printf("open file %s failed\n",argv[1]);
  20.     exit(1);
  21. }
  22. if((to_fd=open(argv[2],O_CREAT|O_WRONLY,0777))==-1)
  23. {
  24.     printf("open file2 %s failed\n",argv[2]);
  25.     exit(1);
  26. }
  27. while(bytes_read=read(from_fd,buffer,BUFFER_SIZE))
  28. {
  29.      if((bytes_read==-1)&&(errno!=EINTR)) break; /*don't understand~*/
  30.      else if(bytes_read>0)
  31.      {
  32.          ptr=buffer;
  33.     while(bytes_write=write(to_fd,ptr,bytes_read))
  34.     {
  35.     if((bytes_write==-1)&&(errno!=EINTR)) break;
  36.     else if(bytes_write==bytes_read) break;
  37.      else if(bytes_write>0)
  38.      {
  39.       ptr+=bytes_write;
  40.       bytes_read-=bytes_write; /*don't understand*/
  41.       }
  42.     }
  43.      }
  44. }
  45.     close(from_fd);
  46.     close(to_fd);
  47.     exit(0); /*the diffrence between exit(0) and (1) find it~!!*/
  48. }

阅读(590) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:Linux系统下execl函数特点

给主人留下些什么吧!~~