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;
}
相关推荐
cuisidong199719 分钟前
如何在 Kali Linux 上安装 Google Chrome 浏览器
linux·运维·chrome
光通信学徒1 小时前
ubuntu图形界面右上角网络图标找回解决办法
linux·服务器·ubuntu·信息与通信·模块测试
南种北李1 小时前
Linux自动化构建工具Make/Makefile
linux·运维·自动化
小飞猪Jay1 小时前
面试速通宝典——10
linux·服务器·c++·面试
暗恋 懒羊羊2 小时前
Linux 生产者消费者模型
linux·开发语言·ubuntu
安红豆.3 小时前
Linux基础入门 --13 DAY(SHELL脚本编程基础)
linux·运维·操作系统
..空空的人3 小时前
linux基础指令的认识
linux·运维·服务器
penny_tcf3 小时前
Linux基础命令halt详解
linux·运维·服务器
荣世蓥4 小时前
10.2 Linux_进程_进程相关函数
linux·运维·服务器
安全不再安全5 小时前
Linux 安装 yum
linux·运维·centos