在C语言中要用到write和read函数要用到什么头文件

在C语言中要用到write和read函数要用到什么头文件,第1张

1、要用到unistd.h头文件

2、 Write函数

用法:

write函数所在的头文件为 <unistd.h>

write有两种用法。一种是:

ssize_twrite(int handle, void *buf, int nbyte)

handle 是文件描述符;

buf是指定的缓冲区,即指针,指向一段内简猜存单元;

nbyte是要写入文件指定的字节数;返回值:写入文档的字节数(成功);-1(出错)

write函数把buf中nbyte写入文件描述符handle所指的文档,成功时返回写的字节数,错误时返回-1.

另一种是:write(const char* str,int n)

str是字符指针或字符数组,用来存放一个字符串。n是int型数,它用来表示输出显示字符串中字符的个数。

write("string",strlen("string")表示输出字符串常量

3、程序示例:

#include <stdio.h>

#include <stdlib.h>

#include <fcntl.h>

#include <sys\stat.h>

#include <io.h>

#include <string.h>

int main(void)

{

int *handle char string[40]

int length, res/* Create a file named "TEST.$$$" in the current directory and write a string to it. If "TEST.$$$" already exists, it will be overwritten. */

if ((handle = 拦唯型open("TEST.$$$", O_WRONLY | O_CREAT | O_TRUNC, S_IREAD | S_IWRITE)) == -1)

{

printf("Error opening file.\n")

exit(1)

}

strcpy(string, "Hello, world!\n")

length = strlen(string)

if 山和((res = write(handle, string, length)) != length)

{

printf("Error writing to the file.\n")

exit(1)

}

printf("Wrote %d bytes to the file.\n", res)

close(handle) return 0 }

read是标准的C/仿粗C++函数,头文件为io.h原型为int read(int handle, void *buf, unsigned len)它与scanf最大的稿知区别,它是系统最低层函数,scanf是通过它来键大消实现的

read()函数的原型是int read(int fd,void *buf,int count)。它的功能是“从文件说明符fd相关联的文件中读取count个字符,并把这些字符存储到袭数buf所指的缓冲区中。返回值是 *** 作成功时所读到的字节数,升游在文件结束时可能少于count个字节;若返回值为-1则说明出错了,返回0则表示到达文件尾端。例:从文件ABC.txt中读取前100个字节存入数组buffer中——

#include "stdin.h"

#include "io.h"

#include "fcnt1.h"

int main(void){

int fd

char buffer[100]

if((fd=open("ABC.txt"拍笑首,O_RDONLY))==-1){

printf("Can't open file.\n")

exit(-1)

}

if(read(fd,buffer,100)!=100)

printf("Possible read error!\n")

}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/tougao/12236206.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-22
下一篇2023-05-22

发表评论

登录后才能评论

评论列表(0条)

    保存