[元旦散分] 文件读写代码
之前贴的那个因照顾有人可能用旧式编译器,使用了不安全的函数,现在换用安全函数,并加上返回错误代码,让调用者有更大的可控性。不多作解释,只要阅读者看得到修改结构体结构、数组尺寸之类是否需要改读写函数,以及如果用链表作数据结构则读写函数要作什么改动即可。
解释一下程序的动作:
1.初始化两条记录的数据,写入到文件中。
2.在内存中修改原先两条记录中的第一条记录的数据。
3.从文件中读入一条记录追加到当前数据的末尾,令数组成为三条记录。
4.在屏幕输出这三条记录,确认再读出来的肯定不是留在内存中的原数据,而是的确从文件中读回来的。
5.注意:a.文件读写函数没有与数据结构密切相关的代码,随便修改结构体也不会有影响,唯一有影响的,是如何递增记录,数组和链表是不一样的;b.采用字符串cz模式使用结构体数组,即有结束标志,无需传递有效元素个数。
程序代码:
#include <Windows.h>
#include <stdio.h>
#include <string.h>
#include <conio.h>
typedef struct _student
{
char clas[20]; /*班级*/
int number; /*学号*/
char name[20]; /*姓名*/
float clan; /*C语言成绩*/
float english; /*大学英语成绩*/
float math; /*高等数学成绩*/
float sum; /*总分*/
float adver; /*平均分*/
} Student;
const char fileName[] = "Students.DAT";
errno_t SaveData(Student* stu);
errno_t LoadData(Student* stu, int number);
void ShowData(Student* stu);
void main(void)
{
Student stu[50] = {
{ "中文10(1)", 1, "张三丰", 80.5, 70.0, 92.5 },
{ "中文10(1)", 2, "丘处机", 77.0, 60.0, 95.0 },
{ NULL }
};
SaveData(stu);
strcpy_s(stu[0].clas, sizeof(stu[0].clas) / sizeof(char) - 1, "中文10(2)");
strcpy_s(stu[0].name, sizeof(stu[0].name) / sizeof(char) - 1, "梅超风");
stu[0].clan = 60.5;
stu[0].english = 74.0;
stu[0].math = 80.0;
LoadData(&stu[2], 1);
ShowData(stu);
_getch();
}
errno_t SaveData(Student* stu)
{
FILE* file;
errno_t err;
if (!(err = fopen_s(&file, fileName, "wb")))
{
while (*stu->clas)
{
fwrite((void *)stu, sizeof(*stu), 1, file);
++stu;
}
fclose(file);
}
return err;
}
errno_t LoadData(Student* stu, int number)
{
FILE* file;
errno_t err;
if (!(err = fopen_s(&file, fileName, "rb")))
{
while (!feof(file) && number--)
{
fread(stu, sizeof(*stu), 1, file);
++stu;
}
fclose(file);
*stu->clas = NULL;
}
return err;
}
void ShowData(Student* stu)
{
while (*stu->clas)
{
printf("班级: %-20s\n", stu->clas);
printf("学号: %04d\n", stu->number);
printf("姓名: %-20s\n", stu->name);
printf("C语言: %6.2f\n", stu->clan);
printf("英语: %6.2f\n", stu->english);
printf("高数: %6.2f\n", stu->math);
printf("\n");
++stu;
}
}
[ 本帖最后由 TonyDeng 于 2011-12-31 15:34 编辑 ]









接分了
