现在的位置: 首页 > 综合 > 正文

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

2013年10月11日 ⁄ 综合 ⁄ 共 1030字 ⁄ 字号 评论关闭
unix/Linux 低级IO函数的用法read && write
简单的读一个文件:

#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;

抱歉!评论已关闭.