C 语言 fwrite()

fwrite() 函数在 stdio.h 头文件中定义。它有助于将数据从 ptr 指向的数组写入到指定的流中。


size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream); #where stream should be a file pointer

 

fwrite() 参数: 

fwrite() 函数接受四个参数。此函数主要用于写入二进制数据,它是 fread() 函数的补充函数。

参数 描述 必需/可选
ptr 指向要写入的元素数组的指针 必需
size 要写入的每个元素的字节大小 必需
nmemb 元素数量,每个元素大小为 size 字节 必需
stream 指向 FILE 对象的指针,该对象指定输出流 必需

fwrite() 返回值

fwrite() 函数的返回值为成功写入的元素总数。它以 size_t 对象返回,这是一种整型数据类型。

输入 返回值
成功 等同于 nmemb 的整数值
错误或文件结束符 (EOF) 小于 nmemb 的值

fwrite() 示例 

示例 1:C 语言中 fwrite() 函数的工作方式是什么?


#include <stdio.h>
#include <string.h>
int main()
{
   FILE *pnt;
   char st[] = "Welcome to C Programming";

   pnt = fopen( "myfile.txt" , "w" );
   fwrite(st , 1 , sizeof(st) , pnt );

   fclose(pnt);
  
   return(0);
}

输出


Welcome to C Programming

示例 2:C 语言中 fwrite() 如何工作?


#include <stdio.h>

int main (){
   FILE *pnt;
     int cnt;
     char ar[6] = "hello";
 
     pnt = fopen("mysample.txt", "wb");
     cnt = fwrite(ar, 1, 5, pnt);
     fclose(pnt);
 
     return 0;
}

输出


/*opens a file named sample.txt, writes an array of characters(below text) to the file, and closes it. */
hello