Linux 文件读写

函数的详细介绍可以用man命令来查看,例如 man 2 open.

open

#include <fcntl.h>

int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);

The open() system call opens the file specified by pathname. If the specified file does not exist, it may optionally (if O_CREAT is specified in flags) be created by open().

The return value of open() is a file descriptor, a small, nonnegative integer that is used in subsequent system calls (read(2), write(2), lseek(2), fcntl(2), etc.) to refer to the open file.The file descriptor returned by a successful call will be the lowest-numbered file descriptor not currently open for the process.

lseek

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

off_t lseek(int fd, off_t offset, int whence);

DESCRIPTION
lseek() repositions the file offset of the open file description associated with the file descriptor fd to the argument offset according to the directive whence as follows:

   SEEK_SET
          The file offset is set to offset bytes.

   SEEK_CUR
          The file offset is set to its current location plus offset bytes.

   SEEK_END
          The file offset is set to the size of the file plus offset bytes.

lseek() allows the file offset to be set beyond the end of the file (but this does not change the size of the file). If data is later written at this point, subsequent reads of the data in the gap (a “hole”) return null bytes (‘\0’) until data is actually written into the gap.

write

#include <unistd.h>

ssize_t write(int fd, const void *buf, size_t count);

DESCRIPTION
write() writes up to count bytes from the buffer starting at buf to the file referred to by the file descriptor fd.

read

#include <unistd.h>

ssize_t read(int fd, void *buf, size_t count);

DESCRIPTION
read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf.

On files that support seeking, the read operation commences at the file offset, and the file offset is incremented by the number of bytes read. If the file offset is at or past the end of file, no bytes are read, and read() returns zero.

示例

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


int main(){
    int fd;
    int write_data = 10;
    int read_data;
    fd = open("file",O_RDWR | O_CREAT,0644);  //打开文件,若不存在就创建,权限:可读可写+可读+可读
    lseek(fd,SEEK_SET,0);   //设置写位置
    write(fd,(char*)&write_data,sizeof(write_data));  //写入数据
    lseek(fd,SEEK_SET,0);   //设置读位置
    read(fd,(char*)&read_data,sizeof(read_data));   //读取数据
    printf("%d\r\n",read_data);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

忆昔z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值