1.Linux应用编程---文件I/O(open、read、write、lseek、close)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wang328452854/article/details/50474553

文件描述符

定义:对内核而言,文件描述符相当于一个文件的标识,它是一个非负整数,当打开(open)一个现有文件或者创建(creat)一个新文件时,内核会向进程返回一个文件描述符
在unix中(文件描述符 0–标准输入 1–标准输出 2–标准错误)

open

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int open(const char *pathname, int oflag, .../*mode_t  mode*/)

参数1:打开或者创建文件的名字
参数2:选项参数,可选择多个参数用 | 构成
其中: O_RDONLY 只读打开 O_WRONLY只写打开 O_RDWR读写打开只能选择一个
下面是可选择的
O_APPEND 每次都追加在文件的尾端
O_CREAT 若文件不存在,则创建它,使用此项,需要指定第三个参数mode,用于设定新文件的权限
O_EXCL 若指定了O_CREAT,而文件存在则会报错,用于测试一个文件是否存在,不存在则创建
O_TRUNC 如果此文件存在,而且为只写或读写成功打开,则将其长度截为0
参数3:…表示余下参数的数量和类型根据具体调用会有所不同,通常创建新文件时才使用表示权限

read

#include <unistd.h>
size_t read(int fd,void *buf,size_t nbytes)

描述:从文件描述符相关联的文件里读入nbytes个字节的数据,把它们放到数据区buf中,并返回读入的字节数
参数1:文件描述符
参数2:存放从文件中读取的数据的存储区
参数3:读出的字节数
返回值
0 未读入任何数据,已达文件尾
-1 表示出错
其它 读出的字节数

write

#include <unistd.h>
size_t write(int fd,const void *buf,size_t nbytes)

描述:把缓冲区buf前nbytes个字节写入文件描述符fd相关联的文件中,返回实际写入的字节数
参数1:文件描述符
参数2:写入文件的缓冲区指针
参数3:读出的字节数
返回值
0 未写入任何数据
-1 表示出错
其它 写入的字节数

lseek

#include <unistd.h>
off_t lseek(int fd,off_t offset,int whnece)

描述:移动文件指针到指定位置
参数1:文件描述符
参数2:偏移量,具体与第三个参数有关
参数3:SEEK_SET 文件头 SEEK_CUR 当前位置 SEEK_END 文件尾

close

#include <unistd.h>
int close(int fd)

描述:关闭一个打开的文件
参数1:文件描述符
返回值
小于0 关闭失败
其它 关闭成功

下面根据上述写一个综合案例

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

int main(int argc, char **argv)
{
    int fd,size;
    char* buf = "hello,I'm wxp,this is my job!";
    char buf_r[20];
    int len = strlen(buf);//数组长度

    printf("len = %d\n",len);


    /*调用open创建wxp.c*/
    if((fd = open("./wxp.c",O_CREAT|O_TRUNC|O_RDWR,0666)) < 0)
    {
        printf("open fail\n");
        exit(1);
    }
    else
    {
        printf("open file: wxp.c fd = %d\n",fd);
    }


    /*write写入*/
    if((size = write(fd,buf,len)) < 0)
    {
        printf("write fail\n");
        exit(1);
    }
    else
    {
        printf("write: %s\n",buf);
        printf("write size = %d\n",size);
    }

    /*lseek函数移动文件指针位置到文件开头*/
    lseek(fd,0,SEEK_SET);
    if((size = read(fd,buf_r,15)) < 0)
    {
        printf("read fail\n");
        exit(1);
    }
    else
    {
        buf_r[15] = '\0';
        printf("read from wxp.c the content is %s\n",buf_r);
        printf("read size = %d\n",size);
    }

    if(close(fd) < 0)
    {
        printf("close fail\n");
        exit(1);
    }
    else
    {
        printf("close wxp.c\n");
    }
    return 0;

}

运行结果如下:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/wang328452854/article/details/50474553