C语言编程删除文件中指定结构体的数据
时间: 2023-10-01 18:05:53 浏览: 285
删除文件中指定结构体的数据可以按照以下步骤进行:
1. 打开要操作的文件,使用fopen函数,打开方式为“rb+”(读写二进制文件)。
2. 定义一个与文件中存储的结构体相同的结构体变量,用于读取文件中的数据。
3. 定义一个新的结构体变量,用于存储要删除的数据。
4. 使用fread函数读取文件中的数据,并将读取到的数据存储到结构体变量中。
5. 判断读取到的结构体变量中的数据是否为要删除的数据,如果是,跳过该数据,否则将该数据写入一个临时文件中。
6. 重复步骤4和步骤5,直到文件中的所有数据都被读取完毕。
7. 关闭原文件和临时文件。
8. 删除原文件。
9. 将临时文件重命名为原文件的名称。
下面是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct student {
char name[20];
int age;
float score;
};
int main() {
FILE *fp, *temp_fp;
struct student stu, del_stu;
int found = 0;
fp = fopen("students.dat", "rb+");
if (fp == NULL) {
printf("Failed to open file.\n");
exit(1);
}
temp_fp = fopen("temp.dat", "wb");
if (temp_fp == NULL) {
printf("Failed to create temp file.\n");
exit(1);
}
printf("Enter the name of the student to delete: ");
scanf("%s", del_stu.name);
while (fread(&stu, sizeof(struct student), 1, fp) == 1) {
if (strcmp(stu.name, del_stu.name) == 0) {
found = 1;
printf("Deleted student: %s\n", stu.name);
} else {
fwrite(&stu, sizeof(struct student), 1, temp_fp);
}
}
if (!found) {
printf("No student with name %s found.\n", del_stu.name);
}
fclose(fp);
fclose(temp_fp);
remove("students.dat");
rename("temp.dat", "students.dat");
return 0;
}
```
在这个示例代码中,我们打开了一个名为“students.dat”的二进制文件,其中存储了多个学生的信息。我们要删除文件中的一个学生信息,可以根据用户输入的学生姓名查找要删除的学生,然后将其他学生信息写入一个临时文件中。最后,删除原文件并将临时文件重命名为原文件的名称。
阅读全文
相关推荐


















