C language: read student's basic data from a file, calculate and sort, and then write it into another file

The idea of ​​this program:
1. Call the read DAT function to enter student information.
2. Arrange the information by calling the sortDAT function and the calDAT function.
3. Print the sorted data through the print DAT function to observe whether it is accurate and whether the function is effective
4. Save the sorted data into the writeDAT function again

The general grammar of the subsequent program is relatively simple, combined with structure.
Involving #include <conio.h> this header file.

Code display:

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

#define N 10

struct STU
{
    
    
	int num;
	char name[12];
	double score[4];
	double sum;
	double ave;
};

void readDAT(struct STU p[], int n);
void writeDAT(struct STU p[], int n);
void sortDAT(struct STU p[], int n);
void calDAT(struct STU p[], int n);
void printDAT(struct STU p[], int n);

int main(void)
{
    
    
	struct STU st[N] = {
    
    0};

	readDAT(st, N);
	printDAT(st, N);
	calDAT(st, N);
	sortDAT(st, N);
	printf("\nAfter Sort:\n");
	printDAT(st, N);
	writeDAT(st, N);
	return 0;
}

void readDAT(struct STU p[], int n)
{
    
    
	int i, j;
	double temp;
	FILE *fp;
	
	if ((fp = fopen("stu.dat", "r")) == NULL)
	{
    
    
		printf("cannot open file stu.dat!\n");
		exit(0);
	}
	for (i = 0; i < n; i++)
	{
    
    
		fscanf(fp,"%d%s", &p[i].num, p[i].name);
		for (j = 0; j < 4; j++)
		{
    
    
			fscanf(fp, "%lf", &temp);
			p[i].score[j] = temp;
		}
	}
	fclose(fp);
}

void writeDAT(struct STU p[], int n)
{
    
    
	int i, j;
	FILE *fp;
	
	if ((fp = fopen("out.dat", "w")) == NULL)
	{
    
    
		printf("cannot open file out.dat!\n");
		exit(0);
	}
	for (i = 0; i < n; i++)
	{
    
    
		fprintf(fp,"%5d %-7s", p[i].num, &p[i].name);
		for (j = 0; j < 4; j++)
		{
    
    
			fprintf(fp, "%5.1f", p[i].score[j]);
		}
		fprintf(fp, "%6.1f%5.1f\n", p[i].sum, p[i].ave);
	}
	fclose(fp);
}

void sortDAT(struct STU p[], int n)
{
    
    
	int i,j;
	struct STU temp;
	for(i=0;i<n;i++)
	{
    
    
		for(j=0;j<n-i-1;j++)
		{
    
    
			if(p[j].num>p[j+1].num)
			{
    
    
				temp=p[j];
				p[j]=p[j+1];
				p[j+1]=temp;
			}
		}
	}
}

void calDAT(struct STU p[], int n)
{
    
    
	int i,j;
	double s=0;
	for(i=0;i<n;i++)
	{
    
    
		for(j=0;j<4;j++)
		{
    
    
			s=p[i].score[j]+s;
		}
        p[i].sum=s;
		p[i].ave=p[i].sum/4;
		s=0;
	}
}

void printDAT(struct STU p[], int n)
{
    
    
	int i, j;
	for (i = 0; i < n; i++)
	{
    
    
		printf("%5d %-7s", p[i].num, p[i].name);
		for (j = 0; j < 4; j++)
		{
    
    
			printf("%5.1f", p[i].score[j]);
		}
		printf("%6.1f%5.1f\n", p[i].sum, p[i].ave);
	}
}

Guess you like

Origin blog.csdn.net/yooppa/article/details/114670971