C语言fwrite函数了解

来源:互联网 发布:unity3d eventsystem 编辑:程序博客网 时间:2024/06/09 20:09

fwrite()函数----write data to a stream

原型:

size_t fwrite(const void* buffer, size_t size, size_t count, FILE* stream);

注意:这个函数以二进制形式对文件进行操作,不局限于文本文件

demo:

[cpp] view plain copy
  1. #include <stdio.h>  
  2. #include <process.h>  
  3. typedef struct   
  4. {  
  5.     int i;  
  6.     char ch;  
  7. }mystruct;  
  8. int main()  
  9. {  
  10.     FILE *stream;  
  11.     mystruct s;  
  12.     /*wb只写打开或新建一个二进制文件;只允许写数据。*/  
  13.     if ((stream=fopen("test.$$$","wb"))==NULL)  
  14.     {  
  15.         fprintf(stderr,"cannot open output file.\n");  
  16.         return 1;  
  17.     }  
  18.     s.i=0;  
  19.     s.ch='A';  
  20.     fwrite(&s,sizeof(s),1,stream);  
  21.     fclose(stream);  
  22.     stream=NULL;  
  23.     system("pause");  
  24.     return 0;  
  25. }  

demo2:

[cpp] view plain copy
  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.     FILE *pFile=NULL;  
  5.     char buffer[]={'x','y','z'};  
  6.     pFile=fopen("myfile.bin","wb");  
  7.     fwrite(buffer,sizeof(buffer),1,pFile);  
  8.     fclose(pFile);  
  9.     system("pause");  
  10.     return 0;  
  11. }  

demo3:

[cpp] view plain copy
  1. #include <stdio.h>  
  2. #include <process.h>  
  3. int main()  
  4. {  
  5.     FILE *fp=NULL;  
  6.     char msg[]="file content";  
  7.     char buf[20];  
  8.     fp=fopen("c:\\a.txt","w+");    //二级目录会不成功  
  9.     if (NULL==fp)  
  10.     {  
  11.         printf("The file doesn't exist!\n");  
  12.         getchar();  
  13.         getchar();  
  14.         return -1;  
  15.     }  
  16.     fwrite(msg,strlen(msg),1,fp);   //把字符串内容写入到文件  
  17.     fseek(fp,0,SEEK_SET);           //定位文件指针到文件首位置  
  18.     fread(buf,strlen(msg),1,fp);    //把文件读入到缓存  
  19.     buf[strlen(msg)]='\0';          //删除缓存内多余空间  
  20.     printf("buf=%s\n",buf);  
  21.     printf("strlen(buf) = %d\n",strlen(buf));  
  22.     system("pause");  
  23.     return 0;  
  24. }  
0 0
原创粉丝点击