#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//函数声明
void readfile_Function();
void Savefile_Function();
//读文件函数
void readfile_Function() {
FILE *fp;
char name[20],
address[20],
phone[20];
int age = 0;
if ((fp = fopen("1.txt", "r")) == NULL) { //判断文件是否存在及可读
printf("不能打开该文件1\n");
exit(0);
}
else
{
printf("正在从文件中读取信息,请稍后...\n\n");
while (fscanf(fp, "%s%s%d%s", name, address, &age, phone) != EOF)
{
printf("%s\t %s\t %d\t %s\n", name, address, age, phone);
}
fclose(fp);
}
}
//写文件函数
void Savefile_Function()
{
FILE *fp;
if ((fp = fopen("1.txt", "a+")) == NULL)
{
printf("打开文件失败,请建立文件");
}
fprintf(fp, "%s%c%s%c%d%c%s%c","章邯", ' ', "秦国", ' ', 25, ' ', "1256224645631", '\n');
fclose(fp);
readfile_Function();
printf("保存结束\n");
printf("\n\n");
}
//主函数测试
int main() {
//文件操作函数
readfile_Function();
Savefile_Function();
return 0;
}
添加前
运行测试
添加后