我想做一个C语言程序,功能:用户输入名字和分数,将这些信息写入文件,当用户再次输入相同的名字时,显示该用户的最各次分数
时间: 2024-05-12 13:19:28 浏览: 8
以下是一个示例程序,实现了您所描述的功能:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LEN 20 // 假设名字最长为20个字符
#define FILENAME "score.txt"
struct student {
char name[MAX_NAME_LEN];
int score;
};
int main() {
FILE *fp;
struct student stu;
char input_name[MAX_NAME_LEN];
int input_score;
int found = 0;
// 打开文件,如果不存在则创建
fp = fopen(FILENAME, "a+");
if (fp == NULL) {
printf("无法打开文件 %s\n", FILENAME);
exit(EXIT_FAILURE);
}
// 读入用户输入的名字和分数
printf("请输入您的名字:");
scanf("%s", input_name);
printf("请输入您的分数:");
scanf("%d", &input_score);
// 在文件中查找是否已存在该名字的记录
rewind(fp); // 将文件指针移动到文件开头
while (fread(&stu, sizeof(struct student), 1, fp) == 1) {
if (strcmp(stu.name, input_name) == 0) {
found = 1;
if (input_score > stu.score) {
// 如果用户输入的分数比之前的高,更新分数
stu.score = input_score;
fseek(fp, -sizeof(struct student), SEEK_CUR); // 将文件指针移到当前记录的位置
fwrite(&stu, sizeof(struct student), 1, fp);
printf("您的最高分是 %d\n", input_score);
} else {
// 如果用户输入的分数不如之前的高,保留原分数
printf("您的最高分是 %d\n", stu.score);
}
break;
}
}
if (!found) {
// 如果文件中没有该名字的记录,添加新记录
strcpy(stu.name, input_name);
stu.score = input_score;
fwrite(&stu, sizeof(struct student), 1, fp);
printf("您的最高分是 %d\n", input_score);
}
// 关闭文件
fclose(fp);
return 0;
}
```
程序的基本思路是打开文件、读入用户输入、在文件中查找是否已存在该名字的记录、如果存在则更新分数,否则添加新记录,最后关闭文件。其中,用到了结构体来保存每个学生的名字和分数,使用strcmp函数比较字符串是否相同,使用fseek函数移动文件指针,使用fwrite函数写入结构体数据到文件中。