// 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的博客-优快云博客