Dotcpp  >  编程教程  >  io.h头文件  >  C语言write()函数:写文件

C语言write()函数:写文件

点击打开在线编译器,边学边练

函数名:write

头文件:<io.h>

函数原型: int write(int handle,void *buf,int len);

功能:获取打开文件的指针位置

参数:int handle  为要获取文件指针的文件句柄

          void *buf   为要写入的内容

          int len     为要写入文件的长度

返回值:返回实际写入文件内容的长度


程序例:将字符串写入文件,并读取文件中的字符串,输出结果

#include<stdio.h>

#include<io.h>

#include<fcntl.h>

#include<string.h>

int main(void){

   int fd=open("D:\\a.txt",O_RDWR+O_CREAT);

   if(fd==-1){

      printf("can not open the file\n");

      return 1;

   }

   char buf[1024]={"I love www.dotcpp.com very much!"},buf2[1024]={"\0"};

   int len=write(fd,buf,strlen(buf));

   lseek(fd,0,SEEK_SET);

   int len2=read(fd,buf2,1024);

   printf("%s\nlen=%d\n",buf2,len);

   close(fd);

   return 0;

}

 

运行结果

I love www.dotcpp.com very much!
len=32



本文固定URL:https://www.dotcpp.com/course/463

C语言函数库
assert.h头文件
ctype.h头文件
float.h头文件
io.h头文件
math.h头文件
mem.h头文件
setjmp.h头文件
stdio.h头文件
stdlib.h头文件
sigal.h头文件
string.h头文件
time.h头文件
Dotcpp在线编译      (登录可减少运行等待时间)