对上一节做的补充
f_seriesnewagain9.c
#include <stdio.h>#include <string.h>int main(){//FILE *fopen(const char *pathname, const char *mode);FILE *fp;char *str = "ganboss is very handsome";char readBuf[128] = {0};fp = fopen("./gannew.txt","w+");//size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream);// ptr buf// size sizeof(char)//geshu//which fileint nwrite = fwrite(str,sizeof(char),strlen(str),fp);//fwrite(str,sizeof(char)*strlen(str),1,fp);//int fseek(FILE *stream, long offset, int whence);fseek(fp,0,SEEK_SET);//size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);int nread = fread(readBuf,sizeof(char),strlen(str),fp);printf("read data: %s\n",readBuf);printf("read = %d,write = %d\n",nwrite,nread);return 0;}
增加了 这个
printf("read = %d,write = %d\n",nwrite,nread);
运行结果为:
对比 代码
#include <stdio.h>#include <string.h>int main(){//FILE *fopen(const char *pathname, const char *mode);FILE *fp;char *str = "ganboss is very handsome";char readBuf[128] = {0};fp = fopen("./gannew.txt","w+");//size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream);// ptr buf// size sizeof(char)//geshu//which fileint nwrite = fwrite(str,sizeof(char)*strlen(str),1,fp);//fwrite(str,sizeof(char)*strlen(str),1,fp);//int fseek(FILE *stream, long offset, int whence);fseek(fp,0,SEEK_SET);//size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);int nread = fread(readBuf,sizeof(char)*strlen(str),1,fp);printf("read data: %s\n",readBuf);printf("read = %d,write = %d\n",nwrite,nread);return 0;}
int nwrite = fwrite(str,sizeof(char),strlen(str),fp);int nread = fread(readBuf,sizeof(char),strlen(str),fp);int nwrite = fwrite(str,sizeof(char)*strlen(str),1,fp);int nread = fread(readBuf,sizeof(char)*strlen(str),1,fp);
区别这两段的代码 分别是上下两个结果
运行结果为:
当 fwrite 和 fread 的size_t nmemb 为多少 打印出来就是多少
标准c库写入结构体到文件
#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <stdio.h>#include <unistd.h>#include <string.h>#include <stdlib.h>struct Test{int a;char c;};int main(){FILE *fp;struct Test data1 = {100,'a'};struct Test data2;fp = fopen("./file1","w+");int n_write = fwrite(&data1,sizeof(struct Test),1,fp);fseek(fp,0,SEEK_SET);int n_read = fread(&data2,sizeof(struct Test),1,fp);printf("read : %d,%c\n",data2.a,data2.c);fclose(fp);return 0;}
运行结果为 :
fput、fget、feof
otherf_series11.c //fput
#include <stdio.h>int main(){FILE *fp;fp = fopen("./ganboss.txt","w+");fputc('a',fp);fclose(fp);return 0;}
otherf_series12.c //fput
#include <stdio.h>#include <string.h>int main(){FILE *fp;int i;char *str = "ganboss hen shuai yo!";int len = strlen(str);fp = fopen("./ganboss.txt","w+");for(i=0;i<len;i++){fputc(*str,fp);str++;}fclose(fp);return 0;}
otherf_series13.c //fget、feof
#include <stdio.h>#include <string.h>int main(){FILE *fp;int c;fp = fopen("./ganboss.txt","r");while(!feof(fp)) //nonezero if reach end of file{c = fgetc(fp);printf("%c",c);}fclose(fp);return 0;}