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;
}
相关推荐
虾..4 小时前
Linux 软硬链接和动静态库
linux·运维·服务器
Evan芙4 小时前
Linux常见的日志服务管理的常见日志服务
linux·运维·服务器
hkhkhkhkh1236 小时前
Linux设备节点基础知识
linux·服务器·驱动开发
HZero.chen7 小时前
Linux字符串处理
linux·string
张童瑶7 小时前
Linux SSH隧道代理转发及多层转发
linux·运维·ssh
汪汪队立大功1237 小时前
什么是SELinux
linux
石小千8 小时前
Linux安装OpenProject
linux·运维
柏木乃一8 小时前
进程(2)进程概念与基本操作
linux·服务器·开发语言·性能优化·shell·进程
Lime-30908 小时前
制作Ubuntu 24.04-GPU服务器测试系统盘
linux·运维·ubuntu
百年渔翁_肯肯8 小时前
Linux 与 Unix 的核心区别(清晰对比版)
linux·运维·unix