fwrite()函数----write data to a stream
原型:
size_t fwrite(const void* buffer, size_t size, size_t count, FILE* stream);
注意:这个函数以二进制形式对文件进行操作,不局限于文本文件
demo:
#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:
#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:
#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; }