这个是可以保存txt文件的代码,将录入的信息保存为txt文件,下次打开后还好有信息。
以下是部分代码
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
struct student
{
char name[20];
int num;
double score[3];
double sum;
};
struct stuSystem
{
struct student stu[MAX];
int curSize;
};
struct stuSystem* createSystem()
{
struct stuSystem* pSystem = (struct stuSystem*)
calloc(sizeof(struct stuSystem), 1);
return pSystem;
}
void insertArray(struct stuSystem* pSystem, struct student stuInfo)
{
if (pSystem->curSize >= MAX)
{
printf("无法录入!\n");
return;
}
pSystem->stu[pSystem->curSize] = stuInfo;
pSystem->curSize++;
}
void printArray(struct stuSystem* pSystem)
{
printf("姓名\t编号\t数学\t英语\t体育\t总分\n");
for (int i = 0; i < pSystem->curSize; i++)
{
printf("%s\t%d\t", pSystem->stu[i].name, pSystem->stu[i].num);
for (int j = 0; j < 3; j++)
{
printf("%.1lf\t", pSystem->stu[i].score[j]);
}
printf("%.1lf\n", pSystem->stu[i].sum);
}
}
int searchArray(struct stuSystem* pSystem, const char* name)
{
for (int i = 0; i < pSystem->curSize; i++)
{
if (strcmp(pSystem->stu[i].name, name) == 0)
return i;
}
return-1;
}
void deleteArray(struct stuSystem* pSystem, const char* name)
{
int pos = searchArray(pSystem, name);
if (pos == -1)
{
printf("没找到,无法删除!\n");
}
else
{
for (int i = pos; i < pSystem->curSize - 1; i++)
{
pSystem->stu[i] = pSystem->stu[i + 1];
}
pSystem->curSize--;
printf("删除成功\n");
}
}
void modifyArray(struct stuSystem* pSystem, const char* name)
{
int pos = searchArray(pSystem, name);
if (pos == -1)
{
printf("没找到,无法修改!\n");
}
else
{
printf("请输入该生新的姓名和变化:");
scanf("%s%d", &pSystem->stu[pos].name,&pSystem->stu[pos].num);
printf("请输入新3门课成绩:");
pSystem->stu[pos].sum = 0;
for (int i = 0; i < 3; i++)
{
scanf("%lf", &pSystem->stu[pos].score[i]);
pSystem->stu[pos].sum += pSystem->stu[pos].score[i];
}
printf("修改成功\n");
}
}
void BubbleSortBySum(struct stuSystem* pSystem)
{
for (int i = 0; i < pSystem->curSize; i++)
{
for (int j = 0; j < pSystem->curSize - i - 1; j++)
{
if (pSystem->stu[j].sum < pSystem->stu[j + 1].sum)
{
struct student temp = pSystem->stu[j];
pSystem->stu[j] = pSystem->stu[j + 1];
pSystem->stu[j + 1] = temp;
}
}
}
}
void inputStu(struct stuSystem* pSystem)
{
struct student temp;
printf("请输入学生的姓名和编号:");
scanf("%s%d", &temp.name,&temp.num);
printf("请输入3门课成绩:");
temp.sum = 0;
for (int i = 0; i < 3; i++)
{
scanf("%lf", &temp.score[i]);
temp.sum += temp.score[i];
}
insertArray(pSystem, temp);
}
void saveInfoToFile(struct stuSystem* pSystem, const char* fileName)
{
FILE* save = fopen(fileName, "w");
for (int i = 0; i < pSystem->curSize; i++)
{
fprintf(save, "%s\t%d\t", pSystem->stu[i].name, pSystem->stu[i].num);
for (int j = 0; j < 3; j++)
{
fprintf(save, "%.1lf\t", pSystem->stu[i].score[j]);
}
fprintf(save, "%.1lf\t", pSystem->stu[i].sum);
}
fclose(save);
}