Linux系统编程——文件的写入及读取

写入(write)

使用write函数需要包含以下头文件:

cs 复制代码
#include <unistd.h>

write的函数定义格式

cs 复制代码
ssize_t write(int fd, const void *buf, size_t count);

附加:一般将数据写入文件中后需关闭文件,这里需要调用关闭(close)函数,其包含的头文件与写入函数一样,函数定义格式也比较简洁,如下:

cs 复制代码
int close(int fd);

参数解读:调用该函数时,只需将需要关闭文件的文件描述符fd传进来即可实现关闭

函数定义的参数解读

int fd:fd为创建文件的文件描述符
const void *buf:这里为无类型的指针,通常对他进行强转成字符串:buf为要写入的字节
size_f count:写入字节的长度

整体流程:从定义的buf中写入count个字节并传到文件描述符fd对应的文件

函数返回值

写入成功后会返回写入字节的个数(整型数) ;写入失败会返回**-1**。

代码示例

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

int main()
{
	int fd;
	char *buf = "Hello Word";//将无类型指针强制转换并输入字节
	fd = open("./file1",O_RDWR);
	
	if(fd == -1)
	{
		printf("open file1 failed\n");
		fd = open("./file1",O_RDWR|O_CREAT,0600);
		if(fd > 0)
		{
			printf("creat file1 success\n");
		}
	}
	printf("open success:fd = %d\n",fd);
	write(fd,buf,strlen(buf));
	close(fd);
	return 0;
}

注意:这里计算字符串长度最好用strlen,它能计算出字符串的有效长度,而这里的buf是char型指针,如果用sizeof只能计算出char型在系统中的长度(8个字节),若输入的字符串超过8位,那么使用sizeof只能输入前8位。

读取(read)

使用读取函数时需包含以下头文件

cs 复制代码
#include <unistd.h>

read的函数定义格式

cs 复制代码
ssize_t read(int fd, void *buf, size_t count);

函数定义的参数解读

int fd:fd为创建文件的文件描述符
const void *buf:这里为无类型的指针,通常对他进行强转成字符串:buf为要读取的字节
size_f count:读取字节的长度

整体流程:从文件描述符fd读取count个字节的数据传到buf的缓冲区中。

函数返回值

读取成功后会返回读取字节的个数(整型数) ;读取失败会返回**-1**。

代码示例

cs 复制代码
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
	int fd;
	char *buf = "Hello Word";

	fd = open("./file1",O_RDWR);//文件删除,文件描述符返回值为-1
	
	if(fd == -1)
	{
		printf("open file1 failed\n");
		fd = open("./file1",O_RDWR|O_CREAT,0600);//重新建立一个file1,此时文件描述符返回值大于0
		if(fd > 0)
		{
			printf("creat file1 success\n");
		}
	}
	printf("open success:fd = %d\n",fd);

	int n_write = write(fd,buf,strlen(buf));//定义一个整型变量存放write返回的文件描述符的值(写入字节个数)
	if(n_write != -1)
	{
		printf("write %d byte to file1\n",n_write);
	}
	close(fd);//由于光标问题,写完之后光标在最后面 此时read从光标位置开始读取,并不会读取写入文件中的字符串,需关闭文件并重新打开
	fd = open("./file1",O_RDWR);

 	char *readBuf;
	readBuf = (char *)malloc(sizeof(char)*n_write+1);//对指针进行开辟内存空间,其读取的字节数为写入的字节数,其大小为char型,可用写入字节个数乘以char的值即为读取个数,此时存放的是字符串
	int n_read = read(fd,readBuf,n_write);//定义一个整型变量存放read返回的文件描述符的值(读取字节个数)
	printf("read byte is %d,context is %s\n",n_read,readBuf);
	close(fd);

	return 0;
}
相关推荐
weixin_4370446414 分钟前
Netbox批量添加设备——堆叠设备
linux·网络·python
hhy_smile15 分钟前
Ubuntu24.04 环境配置自动脚本
linux·ubuntu·自动化·bash
宴之敖者、1 小时前
Linux——\r,\n和缓冲区
linux·运维·服务器
LuDvei1 小时前
LINUX错误提示函数
linux·运维·服务器
未来可期LJ1 小时前
【Linux 系统】进程间的通信方式
linux·服务器
Abona1 小时前
C语言嵌入式全栈Demo
linux·c语言·面试
Lenyiin1 小时前
Linux 基础IO
java·linux·服务器
The Chosen One9851 小时前
【Linux】深入理解Linux进程(一):PCB结构、Fork创建与状态切换详解
linux·运维·服务器
Kira Skyler2 小时前
eBPF debugfs中的追踪点format实现原理
linux
2501_927773073 小时前
uboot挂载
linux·运维·服务器