int main()
{
struct StudentType student[1000]={
{1001,"张大仙","男",29,20},
{1002,"大黑龙","龙",158,98},
{1003,"小帅哥","男",65,66},
{1004,"小美女","女",18,55}
};
StudentType *pstudent;
pstudent=student;
int size=sizeof(struct StudentType);
FILE *fp=fopen("C:\\Users\HR\Desktop\555.txt","wb+");
if( (fp=fopen("C:\\Users\HR\Desktop\555.txt","wb+"))==NULL)
{ //以二进制方式打开
puts("Fail to open file!");
return(0);
}
fwrite(pstudent,size,5,fp);
rewind(fp);
fread(pstudent,size,5,fp);
fclose(fp);
wb 不是二进制写入吗?你这写进去的是二进制?
这个目录必须是已经建立好的,C:\Users\HR\Desktop,修改如下,供参考:
#include <stdio.h>
struct StudentType {
int num;
char name[16];
char sex[4];
int age;
int len;
};
int main()
{
struct StudentType student[1000] = {
{1001,"张大仙","男",29,20},
{1002,"大黑龙","龙",158,98},
{1003,"小帅哥","男",65,66},
{1004,"小美女","女",18,55}
};
struct StudentType* pstudent,stu[4]; //修改
pstudent = student;
int size = sizeof(struct StudentType),i; //修改
FILE* fp = fopen("C:\\Users\\HR\\Desktop\\555.txt", "wb+");//"C:\\Users\HR\Desktop\555.txt
if (fp == NULL)//if ((fp = fopen("C:\\Users\HR\Desktop\555.txt", "wb+")) == NULL)
{ //以二进制方式打开
puts("Fail to open file!");
return(0);
}
fwrite(pstudent, size, 4, fp);
rewind(fp);
fread(stu, size, 4, fp);
pstudent = stu; i = 0;
while(i<4){
printf("%d %s %s %d %d\n", pstudent->num, pstudent->name, pstudent->sex, pstudent->age, pstudent->len);
pstudent++; i++;
}
fclose(fp);
}