
1、关键使用这几个函数
int fseek (FILE *stream,long offset,int fromwhere)
long ftell(FILE *stream)
int rewind(FILE *stream)
2、例程:
#include <stdio.h>#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <Windows.h>
/* 读出文件放到数组中,新增数据插入到该数组中;
重新将数组中的数据写入该文件中
*/
void main(int argc,char * agrv)
{
FILE *fp
char name[20] //输入变量
int sum //输入变量
char fName[10][20] //可存储10个人名
int fScore[10] //存储10个分数记录
char buff1[20]
char buff2[20]
int i=0
//打开存储文件
if ((fp=fopen("c:\\scorelist.txt","r"))==NULL)
{
printf("Can not open the file")
getch()
exit(0)
}
else
{
while (!feof(fp))
{
ZeroMemory(buff1,sizeof(buff1)) //清空内存
ZeroMemory(buff2,sizeof(buff1))
fgets(buff1,sizeof(buff1),fp) //读取名称
fgets(buff2,sizeof(buff2),fp) //读取第二行分数
if (strcmp(buff1,"")==0)
{
continue
}
else
{
strcpy(fName[i],buff1)
printf("%s",fName[i]) //输出名称
fScore[i] = atoi(buff2) //将字符型转换成int型
printf("%i\n",fScore[i]) //打印输出分数值
}
i++
}
}
fclose(fp)
//打开存储文件,将排好序的数据重新写入文件中
if ((fp=fopen("c:\\scorelist.txt","w"))==NULL)
{
printf("Can not open the file")
getch()
exit(0)
}
else
{
printf("Input the new name:\n")
scanf("%s",name)
printf("Input the new score:\n")
scanf("%i",&sum)
int j =0
//获取新增积分排序位置
while(sum < fScore[j])
{
j++
}
//移动数据重新对数组排序,从后往前排序
int m = i
while (i>j)
{
strcpy(fName[i],fName[i-1])
fScore[i] = fScore[i-1]
i--
}
strcpy(fName[j],name)
strcat(fName[j],"\n")
fScore[j] = sum
//写入文本文件
int k=0
while(k<=m)
{
fputs(fName[k],fp)
fprintf(fp,"%i\n",fScore[k])
k++
}
}
fclose(fp)
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)