C fwrite

时间:2023-03-08 22:24:55
功能:向文件读入写入一个数据块。

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

(1)buffer:是一个指针,对fwrite 来说,是要输出数据的地址。

(2)size:要写入内容的单字节数;

(3)count:要进行写入size字节的数据项的个数;

(4)stream:目标文件指针。

说明:写入到文件的哪里与文件的打开模式有关,如果是r+,则是从file pointer 指向的地址开始写,替换掉之后的内容,文件的长度可以不变,stream的位置移动count个数。如果是a+,则从文件的末尾开始添加,文件长度加大,而且是fseek函数对此函数没有作用。

demo1:

  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:
  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:
  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. }