生活随笔
收集整理的這篇文章主要介紹了
C语言fwrite函数了解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
fwrite()函數----write data to a stream
原型:
size_t?fwrite(const void* buffer, size_t?size, size_t count, FILE* stream);
注意:這個函數以二進制形式對文件進行操作,不局限于文本文件
demo:
[cpp]?view plaincopy
#include?<stdio.h>?? #include?<process.h>?? typedef?struct??? {?? ????int?i;?? ????char?ch;?? }mystruct;?? int?main()?? {?? ????FILE?*stream;?? ????mystruct?s;?? ?????? ????if?((stream=fopen("test.$$$","wb"))==NULL)?? ????{?? ????????fprintf(stderr,"cannot?open?output?file.\n");?? ????????return?1;?? ????}?? ????s.i=0;?? ????s.ch='A';?? ????fwrite(&s,sizeof(s),1,stream);?? ????fclose(stream);?? ????stream=NULL;?? ????system("pause");?? ????return?0;?? }??
demo2:
[cpp]?view plaincopy
#include?<stdio.h>?? int?main()?? {?? ????FILE?*pFile=NULL;?? ????char?buffer[]={'x','y','z'};?? ????pFile=fopen("myfile.bin","wb");?? ????fwrite(buffer,sizeof(buffer),1,pFile);?? ????fclose(pFile);?? ????system("pause");?? ????return?0;?? }??
demo3:
[cpp]?view plaincopy
#include?<stdio.h>?? #include?<process.h>?? int?main()?? {?? ????FILE?*fp=NULL;?? ????char?msg[]="file?content";?? ????char?buf[20];?? ????fp=fopen("c:\\a.txt","w+");?????? ????if?(NULL==fp)?? ????{?? ????????printf("The?file?doesn't?exist!\n");?? ????????getchar();?? ????????getchar();?? ????????return?-1;?? ????}?? ????fwrite(msg,strlen(msg),1,fp);????? ????fseek(fp,0,SEEK_SET);????????????? ????fread(buf,strlen(msg),1,fp);?????? ????buf[strlen(msg)]='\0';???????????? ????printf("buf=%s\n",buf);?? ????printf("strlen(buf)?=?%d\n",strlen(buf));?? ????system("pause");?? ????return?0;?? }??
總結
以上是生活随笔為你收集整理的C语言fwrite函数了解的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。