linux:系统调用

文件描述符

0       :文件标准输入

1       :文件标准输出

2       :文件输出出错

example:file copy process 

open

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

  int fd=open(char *fname,int how);            //return file discribe char=>0,1,2

  int fd=open(char *fname,int how,mode_t mode);

 file dicribechar     filename      openmode     filequanxian

打开模式:O_RDONLY-只读    O_WRONLY-只写    O_RDWR-读写
附加标志:O_APPEND :表示将文件位置指针移动到文件末尾  
O_TRUNC :将fd所指向的文件内容清空  
O_CREAT :当打开的文件不存在时,自动创建该文件,此时需要mode参数指定文件的权限  
O_EXCL:   
O_NONBLOCK 
 

文件的关闭
   文件操作完毕后必须关闭文件:
    #include <unistd.h>
    int result=close(int fd);

write系统调用

为了使用write系统调用,需要头文件unistd.h,原型如下:
#include <unistd.h>

size_t result     =   write(int filedes      ,  const void *buf,size_t nbytes)

返回实际写入的    Open操作返回的      将buf所指向的存
                                                                        储单元中大小为  
字节大小                文件描述符               Nbytes字节的数据写入          
该调用可以用来在打开的文件中写入信息,若写入不成功,则result=-1

read系统调用

#include <unistd.h>
size_t numread=read(int filedes,const void
*buf,size_t nbytes);

该调用从与文件描述符filedes相关的文件里读 入nbytes个字节的数据,并放到数据区buf里。返回实际读取的字节大小。
若读取 不成功,则nread=-1

逐个字符把一个文件复制到另一个文件

#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>  
#include<stdlib.h>
int main( )
{
char c;
int in,out;
in=open("file.in",O_RDONLY);
  out=open("file.out",O_WRONLY|O_CREAT,S_IWUSR|S_IWOTH);  
while(read(in,&c,1)==1)
write(out,&c,1);
exit(0);

}

[student@localhost Desktop]$ cat file.in
my name is andy.
hello,welcome to c.
hello,c.
[student@localhost Desktop]$ touch file.out

[student@localhost Desktop]$ gcc gyx.c -o gyx

[student@localhost Desktop]$ ./gyx

[student@localhost Desktop]$ cat file.out
my name is andy.
hello,welcome to c.
hello,c.




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值