在vs环境中运行fread函数 发生异常,但是同样的代码在 dev—c中却能正常运行
#include
#include
#include
struct student
{
int id;
char* name;
char* phone;
};
void CreatFile1()
{
FILE* fp = fopen("写入结构体.txt", "w");
if (fp == NULL)
{
perror("写入结构体.txt开启失败");
exit(1);
}
struct student st[] = { 1,"lizhigang","18328746048",2,"liusi","111149223",3,"liyuqi","12345678912" };
fwrite(st, sizeof(struct student), 3, fp);
fclose(fp);
}
void ReadFile1()
{
FILE* ffp = fopen("写入结构体.txt", "r");
if (ffp == NULL)
{
perror("写入结构体.txt开启失败");
exit(1);
}
struct student st[3] = { 0 };
while (1)
{
int i = fread(&st[0], sizeof(struct student), 1, ffp);
if (i == 0)
break;
printf("学号:%d\t姓名:%p\t电话:%p\n", st[0].id, st[0].name, st[0].phone);
}
fclose(ffp);
}
int main(void)
{
//CreatFile1();
// 这里如果在已经创建了文件的情况下 注掉CreatFile1()就不能正常运行,只有这两行都在才能正常运行
ReadFile1();
return 0;
}
先运行CreatFile1(); 在运行 ReadFile1();就行,如果先运行了CreatFile1();
然后注掉在运行ReadFile1();就会报错 不懂是为什么
跟结构体的定义相关,它的 name phone 两个成员只是指针,当用fwrite()函数写入文件时,写入的是只占4个字节或8个字节的字符串在内存里的地址值,所以先运行CreatFile1(); 再运行ReadFile1();就行,如果先运行了CreatFile1(); 然后注掉再单独运行ReadFile1();就会报错,因为那段地址不存在了,这么改:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student
{
int id;
char name[32]; //修改
char phone[32]; //修改
};
void CreatFile1()
{
FILE* fp = fopen("写入结构体.txt", "w");
if (fp == NULL)
{
perror("写入结构体.txt开启失败");
exit(1);
}
struct student st[] = { 1,"lizhigang","18328746048",2,"liusi","111149223",3,"liyuqi","12345678912" };
fwrite(st, sizeof(struct student), 3, fp);
fclose(fp);
}
void ReadFile1()
{
FILE* ffp = fopen("写入结构体.txt", "r");
if (ffp == NULL)
{
perror("写入结构体.txt开启失败");
exit(1);
}
struct student st[3] = { 0 };
while (1)
{
int i = fread(&st[0], sizeof(struct student), 1, ffp);
if (i == 0)
break;
printf("学号:%d\t姓名:%s\t电话:%s\n", st[0].id, st[0].name, st[0].phone);
//printf("学号:%d\t姓名:%p\t电话:%p\n", st[0].id, st[0].name, st[0].phone);
}
fclose(ffp);
}
int main(void)
{
//CreatFile1();
// 这里如果在已经创建了文件的情况下 注掉CreatFile1()就不能正常运行,只有这两行都在才能正常运行
ReadFile1();
return 0;
}