read() / write()函数

Read()

原型

#include <unistd.h> 这个头文件 不加好像也不报错。
ssize_t read(int fd,void* buf,size_t count);
错误返回-1 成功返回 0; count 不能超过最大值SSIZE_MAX (32,767).见
http://blog.chinaunix.net/uid-26858322-id-3311624.html

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main()
{

        int fd = -1;
        ssize_t size =-1,i;
        char buf[10];
        char filename[]= "test.txt";
        fd = open(filename,O_RDONLY); // read only
        if(-1 == fd)
        {

                printf("open file failture");
        }else
        {
                printf("Open success");
        }
        while(size)
        {
                size = read(fd,buf,10);  // read 10 byte;
                if(-1 == size)
                {
                        close(fd);
                }else
                {
                        if(size > 0)
                        {
                                printf("read %d bytes:",size);
                                printf("\"");
                                for(i = 0;i<size;i++)
                                {
                                        printf("%c",*(buf+i));
                                }
                                printf("\"\n");

                        }else
                                printf("reach the end of the file \n");

                }

        }

        return 0;
}

write()函数

原型

ssize_t write(int fd,const void*buf,size_t count);

注:写操作函数并不能保证将数据写入磁盘中,在异步操作中经常出现,write()将数据写入缓冲区,在合适的时机再由系统写入实际设备。可以调用fsync()函数,显示将输入写入设备。


#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
// 写入一个test.txt文件
int main()
{
        // int open(char* filename,int flag,int mode);
        // ssize_t write(int fd,const void* buf,size_t count);
        char*filename = "test.txt";
        int fd = open(filename,O_RDWR);
        if(-1 == fd)
        {
                printf("open file error");
                return -1;
        }else
        {
                char buf[] = "hello world";
                size_t rt = write(fd,buf,strlen(buf));
                if(rt == -1)
                {
                        printf("write error!");
                        close(fd);
                        return -1;
                }else
                {
                        printf("write ok!");

                }
        }
        close(fd);
        return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值