用c语言编写学生档案记录修改:允许用户选择并从文件中读取要修改的学生记录,修改指定的记录 后,能将改记录写回文件中原来的位置
时间: 2024-03-08 14:50:49 浏览: 12
好的,下面是一个简单的C语言程序,实现学生档案记录修改的功能:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_RECORDS 100
#define MAX_NAME_LEN 50
#define MAX_LINE_LEN 256
typedef struct {
int id;
char name[MAX_NAME_LEN];
int age;
} Student;
int read_records(Student records[], char *filename);
void print_record(Student record);
void print_records(Student records[], int count);
int update_record(Student records[], int count, int id);
int main()
{
Student records[MAX_RECORDS];
int count = read_records(records, "students.txt");
printf("Current records:\n");
print_records(records, count);
int id;
printf("Enter the ID of the student you want to update: ");
scanf("%d", &id);
int index = update_record(records, count, id);
if (index == -1) {
printf("Student with ID %d not found.\n", id);
} else {
printf("Updated record:\n");
print_record(records[index]);
FILE *file = fopen("students.txt", "w");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
for (int i = 0; i < count; i++) {
if (i == index) {
fprintf(file, "%d,%s,%d\n", records[i].id, records[i].name, records[i].age);
} else {
fprintf(file, "%d,%s,%d\n", records[i].id, records[i].name, records[i].age);
}
}
fclose(file);
printf("Record updated and file saved.\n");
}
return 0;
}
int read_records(Student records[], char *filename)
{
FILE *file = fopen(filename, "r");
if (file == NULL) {
printf("Error opening file.\n");
exit(1);
}
int count = 0;
char line[MAX_LINE_LEN];
while (fgets(line, MAX_LINE_LEN, file) != NULL) {
char *token = strtok(line, ",");
records[count].id = atoi(token);
token = strtok(NULL, ",");
strcpy(records[count].name, token);
token = strtok(NULL, ",");
records[count].age = atoi(token);
count++;
}
fclose(file);
return count;
}
void print_record(Student record)
{
printf("ID: %d, Name: %s, Age: %d\n", record.id, record.name, record.age);
}
void print_records(Student records[], int count)
{
for (int i = 0; i < count; i++) {
print_record(records[i]);
}
}
int update_record(Student records[], int count, int id)
{
for (int i = 0; i < count; i++) {
if (records[i].id == id) {
printf("Current record:\n");
print_record(records[i]);
printf("Enter new name: ");
scanf("%s", records[i].name);
printf("Enter new age: ");
scanf("%d", &records[i].age);
return i;
}
}
return -1;
}
```
在这个程序中,我们首先定义了一个`Student`结构体,用来表示学生记录。然后定义了一些常量,包括最大记录数、最大姓名长度和最大行长度。接着,我们实现了几个函数:
- `read_records`:从文件中读取学生记录,并返回记录数。
- `print_record`:打印单个学生记录。
- `print_records`:打印所有学生记录。
- `update_record`:根据指定的ID更新学生记录,并返回记录在数组中的下标。
最后,在`main`函数中,我们首先读取文件中的学生记录,并打印出来。然后,让用户输入要修改的学生记录的ID,并调用`update_record`函数进行修改。如果找到了记录,就打印出修改后的记录,并将所有记录写回文件中原来的位置。
这个程序还有很多可以改进的地方,比如输入的合法性检查、文件读写错误处理等。但是,希望这个程序能够帮助您理解如何使用C语言实现学生档案记录修改的功能。