unix/linux系统读写文件

1 open函数需要的头文件

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

函数原型:

int open(const char*pathname,int flags);
int open(const char*pathname,int flags,mode_t mode);

pathname:路径

flags:打开方式 

1)必选:
O_RDONLY只读模式
O_WRONLY只写模式
O_RDWR读写模式
2)可选
 O_APPEND 表示追加: 如果文件已有内容,这次打开文件所写的数据附加到文件的末尾而不覆盖原来的内容。

 O_CREAT 若此文件不存在则创建它。
 使用此选项时需要提供第三个参数mode,表示该文件的访问权限。
 文件权限由open的mode参数和当前进程的umask掩码共同决定
  0777 & (~0002) = 0775
 111111111
 111111101
&
 111111101

O_EXCL 如果同时指定了O_CREAT,并且文件已存在,则出错返回。

O_TRUNC 如果文件已存在,则将其长度截断(Truncate)为0字节。

O_NONBLOCK 设置文件为非阻塞状态


2 close函数需要的头文件

#include<unistd.h>

3read函数  函数原型:ssize_t read(int fd, void *buf, size_t count);  
 从打开的设备或文件中读取数据。
 返回值是读出的字节数的大小
  -1 --> 错误
  >0 --> 读出的字节数
  =0 --> 文件读取完毕

  fd:文件描述符
  buf:数据缓冲区
  count:请求读取的字节数

4write函数  ssize_t write(int fd, const void *buf, size_t count);
 向打开的设备或文件中写数据。


  fd:文件描述符
  buf:需要输出的缓冲区
  count:最大输出字节数
 返回值
  -1 --> 失败
  >=0 --> 写入文件的字节数

案例:

#include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>

int main()
{
        int fd;
        int fd1;
        char buf[2048] = {0};
        int ret = 0;
        char *filename = "/home/cmcc/platform/route/bgpd123/bgp/src/bgp_api.c";
        fd = open(filename,O_RDONLY);
        if(fd == -1)
         {
                perror("error.");
                exit(1);
        }

        fd1 = open("newfile",O_CREAT|O_WRONLY,0777);
        if(fd1 == -1)
        {
                perror("error.");
                exit(1);
        }

        //read file


        int size = read(fd,buf,sizeof(buf));
        if(size == -1)
        {
                perror("error.");
                close(fd);
                close(fd1);
                exit(1);
        }
        while(size > 0)
        {
                //put the read infomation to the newfile.
                ret = write(fd1,buf,size);
                printf("write %d bytes.\n",ret);
                size = read(fd,buf,sizeof(buf));
        }

        close(fd);
        close(fd1);
        return 1;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值