#include<stdio.h>
#define set_s(x,y) {strcpy(s[x].name,y);s[x].size=strlen(y);}
#define nmemb 3
struct test
{
char name[20];
int size;
}s[nmemb];
int main()
{
FILE *fp;
set_s(0,"linux");
set_s(1,"android");
set_s(2,"ios");
int wn;
fp=fopen("D:/c-codeblock/t_write.txt","w+");
wn=fwrite(s,sizeof(struct test),nmemb,fp);
printf("wn=%d\n",wn);
//文件操作完成后,需要将文件关闭
fclose(fp);
//在定义文件指针时,要将文件指针指向空;如 FILE *fp = NULL;
fp=NULL;
return 0;
}
定义函数:size_t fread(void * ptr, size_t size, size_t nmemb, FILE * stream);
函数说明:fread()用来从文件流中读取数据.
参数stream 为已打开的文件指针, 参数ptr 指向欲存放读取进来的数据空间, 读取的字符数以参数size*nmemb 来决定. Fread()会返回实际读取到的nmemb 数目, 如果此值比参数nmemb 来得小, 则代表可能读到了文件的尾或有错误发生, 这时必须用feof()或ferror()来决定发生什么情况.
#include<stdio.h>
#define nmemb 2
struct test
{
char name[20];
int size;
}s[nmemb];
int main()
{
FILE *fp;
int rn;
// fp=fopen("D:/c-codeblock/t.txt","r");
// fp=fopen("D:/c-codeblock/write.txt","r");
fp=fopen("D:/c-codeblock/t_write.txt","r+");
rn=fread(s,sizeof(struct test),nmemb,fp);
printf("rn==%d\n",rn);
fclose(fp);
int i;
for(i=0;i<nmemb;i++)
{
// printf(s);
printf("%d,%20s,%d\n",i,s[i].name,s[i].size);
}
return 0;
}
如果将fwrite的file
通过fgets 读取出来
#include<stdio.h>
int main()
{
char s[1024];
FILE* fp;
int i;
// fp=fopen("D:/c-codeblock/write.txt","r+");
// fp=fopen("D:/c-codeblock/t.txt","r");
// fp=fopen("D:/c-codeblock/write.txt","r");
fp=fopen("D:/c-codeblock/t_write.txt","r+");
while((fgets(s,2,fp))!=NULL)
{
//printf(&s[0]);
printf(&s[0]); //每次读取一个char,完全读取
}
return 0;
}
while((fgets(s,1024,fp))!=NULL) //只能读取linux ,第一行,,为何会是这个结果》》》》???