Linxu系统调用函数---read函数 write函数 lseek函数(详解)

read函数

//头文件
#include <unistd.h>
//原型
 ssize_t read(int fd, void *buf, size_t count);
//功能:read()会把参数fd所指的文件传送count 个字节到buf 指针所指的内存中。
/*返回值:返回值为实际读取到的字节数, 
如果返回0, 表示已到达文件尾或是无可读取的数据。如果返回-1代表读取不成功,错误代码存入errno中*/
//参数:
//1.fd 文件描述符
//2.buf 所要读取内容
//3.count 要读取的大小

write函数

//头文件
#include <unistd.h>
//原型
ssize_t write(int fd, const void *buf, size_t count);
//功能:write()会把参数buf所指的内存写入count个字节到参数fd所指的文件内。
//返回值:返回值write()会返回实际写入的字节数。当有错误发生时则返回-1,错误代码存入errno中。0代表成功
//参数
//1.fd 文件描述符
//2.buf 内容
//3.count 要写的大小

举例:使用read和write函数将大文件写到另外一个文件里

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
int main(){
    //打开已经存在的文件
    int fd = open("test.c",O_RDONLY);
    if(fd == -1){
        perror("open");
        exit(1);
    }
    //创建一个新文件
    int fd1 = open("test-1.c",O_CREAT | O_WRONLY,0664);
    if(fd1 == -1){
        perror("open1");
        exit(1);
    }
    //read file
    char buf[2048] = {0};
    int count = read(fd,buf,sizeof(buf));
    if(count == -1){
        perror("read");
        exit(1);
    }
    while(count){
        //将读出数据写到另一个文件中
        int ret = write(fd1,buf,count);
    	printf("write bytes %d\n",ret);
        //continue read file
        count = read(fd,buf,sizeof(buf));
    }
    close(fd);
    close(fd1);
}

lseek函数

//头文件
#include <sys/types.h>
#include <unistd.h>
//原型
 off_t lseek(int fd, off_t offset, int whence);
/*功能:
lseek是一个用于改变读写一个文件时读写指针位置的一个系统调用。指针位置可以是绝对的或者相对的。功能有三:
1.移动文件指针。每个打开的文件都有一个与其相关联的“当前文件偏移量”(current file offset)。
它通常是一个非负整数,用以度量从文件开始处计算的字节数。通常,读、写操作都从当前文件偏移量处开始,并使偏移量增加所读写的字节数。
按系统默认的情况,当打开一个文件时,除非指定O_APPEND选项,否则该偏移量被设置为0。可以调用lseek显式地为一个打开的文件设置其偏移量。
2.获取文件大小
3.文件拓展*/
//返回值:当调用成功时则返回目前的读写位置,也就是距离文件开头多少个字节。若有错误则返回-1,errno 会存放错误代码。
//参数
//1.fd文件描述符
//2.offset 偏移量
//3.whence 位置
//EEK_SET 将读写位置指向文件头后再增加offset个位移量。
//SEEK_CUR 以目前的读写位置往后增加offset个位移量。
//SEEK_END 将读写位置指向文件尾后再增加offset个位移量。
//当whence 值为SEEK_CUR 或SEEK_END时,参数offet允许负值的出现。

举例

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
int main(){
    int fd = open("aa",O_EDWR);
    if(fd == -1){
        perror("open");
        exit(1);
    }
    //获取文件大小
    int ret = lseek(fd,0,SEEK_END);
    printf("file length = %d\n",ret);
    
    //文件拓展
    ret = lseek(fd,2000,SEEK_END);
    printf("return value %d\n",ret);
    //实现文件拓展,需要再最后做一次写操作
    write(fd,"a",1);
    close(fd);
}
发布了37 篇原创文章 · 获赞 36 · 访问量 3589

猜你喜欢

转载自blog.csdn.net/qq_43799957/article/details/105188985
今日推荐