分享

unix/Linux 低级IO函数的用法read && write

 lchjczw 2012-04-13
简单的读一个文件:

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

int main(int argc,char **argv)
{
        int fd = 0;
        int pid = 0;
        char buffer[20] = {'\0'};
        char *read_buffer[20] = {'\0'};

        //fd = open("/dev/hello",O_RDWR | O_CREAT | O_TRUNC);
        fd = open("/dev/hello",O_RDONLY ); //| O_NONBLOCK);
        printf("fd=%d\n",fd);
        if(fd < 0) {
                perror("/dev/hello");
                return -1;
        }

        read(fd,read_buffer,sizeof(read_buffer)-1);
        printf("read_buffer=%s\n",read_buffer);


        close(fd);

        return 0;
}





---

下面这个就是简单的写一个文件 ,
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc,char **argv)
{
        int fd = 0;
        int pid = 0;
        char buffer[20] = {'\0'};
        char write_buffer[20] = {'\0'};

        strcpy(write_buffer,"zhanglinbao");

        fd = open("/dev/hello",O_RDWR | O_CREAT | O_TRUNC);
        //fd = open("/dev/hello",O_RDONLY);
        printf("fd=%d\n",fd);
        if(fd < 0) {
                perror("/dev/hello");
                return -1;
        }

        write(fd,write_buffer,sizeof(write_buffer)-1);

        close(fd);

        return 0;
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多