嵌入式开发: 文件操作 write 函数

本文深入解析了Unix/Linux系统中的write函数,详细介绍了其在文件操作中的应用。通过实例演示了如何使用write函数进行文件写入,包括函数的参数设置、错误处理及返回值解读。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、函数介绍

write 函数在头文件“#include <unistd.h>”中。

函数原型为 ssize_t write(int fd,const void *buf,size_t count)

参数 fd,使用 open 函数打开文件之后返回的句柄。

参数*buf,需要写入的数据。

参数 count,将参数*buf 中最多 count 个字节写入文件中。

返回值为 ssize 类型,出错会返回-1,其它数值表示实际写入的字节数。

 

二、例程

#include <stdio.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <unistd.h>

#include <string.h>

main()
{
	int fd;
	ssize_t fw;
	char *write_string = "Test Function!!";
	char *path = "/bin/test";
	
	if((fd=open(path, O_RDWR|O_CREAT, 0777)) == -1) 
	{
		perror("open");
	}
	else
	{
		printf("successful create test\n");
	}
	
	fw = write(fd, write_string, strlen(write_string);
	if(fw == -1)
	{
		perror("write");
	}
	else
	{
		printf("write Function OK!\n");
	}
	close(fd);
	
}

在末尾记得 close....

 

三、运行效果

创建且写入成功

目录下的test文件

进入看看里面的内容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值