Linux底层文件基础操作 open(),read(),write()函数介绍

open函数

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

打开已存在的文件
int open(const char *pathname, int flags);
创建一个新文件
int open(const char *pathname, int flags, mode_t mode);

返回值是指向被打开文件的文件描述符,如果发生错误返回-1,产生errno
参数:
-flags:(O_RDONLY O_WRONLY O_RDWR这三个互斥的,含义分别是只读,只写,可读可写)
可选项:O_CREAT 创建新文件的必选项
-mode:设置文件权限,如设置rwxrwxrwx,mode为0777
文件的最终权限为mode&~umask (umask的默认值为0002一般用户)

read函数

#include <unistd.h>
读取文件,输入操作(内存角度)
ssize_t read(int fd, void *buf, size_t count);

返回值为实际读取到的字节数
参数:
-count 表示想要读取到的字节数
-buf 一般为字符数组,用来存放从文件读取到的数据

write函数

#include <unistd.h>
写入文件,输出操作(内存角度)
ssize_t write(int fd, const void *buf, size_t count);

返回值为实际写入的字节数
参数:
-count 表示想要写入的字节数
-buf 用来存放 将要输出到文件的 数据

perror函数

与文件操作配套使用
#include <stdio.h>
根据errno打印错误信息
void perror(const char *s);

参数:
-s:用户设定,一般用来显示哪个函数发生错误
如果是open发生错误,perror(“open”)

下面是对上面几个函数介绍的一个示例
程序作用是从已有文件english.txt中读取全部字节,然后写入到新文件cpy.txt中(cpy.txt是原本不存在的,通过这个程序创建)
示例:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <iostream>
using namespace std;

int main(){
    int srcfd =open("english.txt",O_RDONLY);//打开已有文件
    if(srcfd == -1){
        perror("open");
        return -1;
    }

    int fd = open("cpy.txt",O_WRONLY|O_CREAT,0664);//创建新文件,设置权限为rw_rw_r__
    if(fd == -1){
        perror("open");
        return -1;
    }


    char buf[1024] ={0};
    int len = 0;
    while((len = read(srcfd,buf,sizeof(buf)))>0){//从english.txt中读取数据
        cout<<write(fd,buf,len)<<endl;//写入cpy.txt
    }
    
    close(srcfd);
    close(fd);

    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值