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;
- /*wb只写打开或新建一个二进制文件;只允许写数据。*/
- 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;
- }