write和read系统调用中第三个参数count的值范围

本文通过示例展示了C语言中write和read系统调用的使用。write函数用于向文件写入数据,返回实际写入的字节数,要求count参数不大于buf的长度。read函数从文件读取数据,返回实际读取的字节数,count可以大于等于文件的字节数。示例还解释了count参数的重要性以及可能出现的溢出情况。

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

// C program to illustrate
// write system Call
#include<stdio.h>
#include <fcntl.h>
main()
{
int sz;

int fd = open("foo.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd < 0)
{
	perror("r1");
	exit(1);
}

sz = write(fd, "hello geeks\n", strlen("hello geeks\n"));

printf("called write(% d, \"hello geeks\\n\", %d)."
	" It returned %d\n", fd, strlen("hello geeks\n"), sz);

close(fd);
}

write的作用是对打开的文件fd,执行写入操作,返回值为成功写入的字节数

输出为:

called write(3, "hello geeks\n", 12).  it returned 11


上面的例子显示了当count的值为strlen("hello geeks\n")时,即可正常运行。注意不是sizeof("hello geeks\n")

  • buf至少需要与cnt一样长,因为如果buf的大小小于cnt,那么buf将导致溢出。如写成sizeof的情况。
  • cnt是请求写入的字节数,而返回值是实际写入的字节数。当fd要写入的字节数少于cnt时,就会发生这种情况。

 再看read:

假设sample.txt文件由6个ASCII字符“foobar”组成。那么下面程序的输出是什么?

// C program to illustrate
// read system Call
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdlib.h>

int main()
{
	char c;
	int fd1 = open("sample.txt", O_RDONLY, 0);
	int fd2 = open("sample.txt", O_RDONLY, 0);
	read(fd1, &c, 1);
	read(fd2, &c, 1);
	printf("c = %c\n", c);
	exit(0);
}

read系统调用为fd向buf中写入数据,写入数据的大小为count的值。

输出为:c = f

因此

在read中,count的值可以大于小于或者等于fd中的字节数(最好是大于等于),但是read的返回值始终为向buf缓冲区中写入的字节数。注意若是int c = read(0,buf,100) ,此时在键盘上输入“hello” 敲击回车,则c的值为6,因为算上了回车键。

在write中,count的值要小于等于(最好是等于)buf中的字节数,否则也会出现错误。

参考链接:(38条消息) C语言中的I/O系统调用(Create, Open, Close, Read, Write)_c语言 create write_zsx0728的博客-优快云博客

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值