Linux的文件IO

1. Linux文件IO的基础函数

在Linux中,一切皆文件,所以学习文件IO是执行其他操作的基础。常用的函数有open、write、close、 lseek。

1.1 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.2 write 写文件

#include <unistd.h>

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

1.3 read 读文件

#include <unistd.h>

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

1.4 close 关闭文件

#include <unistd.h>

int close(int fd)

1.5 lseek计算偏移量

对于每个打开的文件,系统都会记录它的读写位置偏移量,我们也把这个读写位置偏移量称为读写偏移

量,记录了文件当前的读写位置,当调用read()或write()函数对文件进行读写操作时,就会从当前读写位置

偏移量开始进行数据读写。

#include <sys/types.h>

#include <unistd.h>

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

2.程序实例

通过一个程序示例,熟悉这个四个函数的用法,首先打开一个文件,然后对其进行读写操作,随后显示读写的内容,并关闭该文件。

cpp 复制代码
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>



//open file

int main(void)
{
char buff[1024];
char buff_w[20]={"9876543210"};
ssize_t fr,fw;
int fd1;
int ret;
int fc;
int i;

fd1 = open("./a.txt", O_RDWR);
if (-1 == fd1){
 	perror("open");
	return fd1;

}


fr =  read( fd1, buff, 15);
if (-1==fr)
	printf("read error!\n");
else
	printf("read data sucessfully!\n");



printf("The data is:\n");

for(i=0;i<15;i++)
{
putchar(buff[i]);

}

printf("\n");


// lseek function
off_t off = lseek(fd1, 0, SEEK_END);
if (-1 == off)
	{

	printf("lseek error\n!");
	}


fw = write(fd1, buff_w,10);
if (-1 == off)
	{

	printf("write error\n!");
	}


fc = close(fd1);

if (-1==fc)
        printf("close error!\n");
else
        printf("close  sucessfully!\n");


}

程序运行的结果:

相关推荐
女神下凡1 小时前
芯易选(152):炬芯(Actions)_开发指南
linux·arm开发·stm32·单片机·嵌入式硬件
zz0723201 小时前
深入浅出 Nginx:核心原理与企业级应用
运维·nginx
智购科技自动售货机厂家2 小时前
自动售货机外设接口与总线设计实战:串口、CAN 与 GPIO 的分工~YH
java·大数据·服务器·数据库·人工智能·单片机·嵌入式硬件
cndes2 小时前
出现 2013 lost connection to MySQL server during query
运维·服务器·数据库
xixiaoyunya2 小时前
服务器备份怎么做?覆盖文件、数据库、虚拟机并落地异地容灾
服务器·数据库·oracle
考虑考虑3 小时前
EMQX认证回调
运维·后端·自动化运维
耗同学一米八3 小时前
湖南省网络建设与运维赛项指导培训:备赛要点全解析
运维·网络·php·网络运维·网络建设与运维·楚怡杯·湖南技能竞赛
qetfw4 小时前
EVE-NG 导入 Debian 虚拟机:VMDK 转 QCOW2 与启动验证
linux·前端·debian·github
master3364 小时前
Linux 用户与权限体系:由浅入深完全指南
linux·运维·服务器
骑着蜗牛撵大象3274 小时前
一次 sendto 一次 recvfrom:UDP 数据报在 Linux 内核里怎么走完一整圈
linux·网络·网络协议·udp·ux·sk_buff·端口分用