下面便是一个更新卡信息文件数据的函数updateCard
int updateCard(const char* CardPath,const Card* pcard,int nIndex)
{//更新卡信息文件中的数据,CardPath为文件路径,pcard为指向要更新的卡信息结点的指针,nIndex为卡信息在文件中的索引号(即在卡信息文件中的行数)
FILE* fp = NULL;
long lpostion = 0;
char string[100] = {0};
char startTime[TIMELENGTH]={0};
char endTime[TIMELENGTH]={0};
char lastTime[TIMELENGTH]={0};
int ncount = 0;
if((fp = fopen(CardPath,"r+")) == NULL)
return FALSE;
while(ncount++<nIndex){
fgets(string,100,fp);
printf("%p\n",(int*)fp);
lpostion = ftell(fp);
}
printf("%p\n",(int*)fp);
//将时间转化为字符串
timeToString(pcard->tStart,startTime);
timeToString(pcard->tEnd,endTime);
timeToString(pcard->tLast,lastTime);
fseek(fp,lpostion,0);
printf("%p\n",(int*)fp);
//向文件中写入数据
//格式为:卡号##密码##状态##开卡时间##截止时间##累积金额##最后使用时间##使用次数##当前余额##删除标识
fprintf(fp,"%s##%s##%d##%s##%s##%0.1f##%s##%d##%0.1f##%d\n",pcard->aName,pcard->aPwd,pcard->nStatus,
startTime,endTime,pcard->fTotalUse,lastTime,pcard->nUseCount,pcard->fBalance,pcard->nDel);
fclose(fp);
return TRUE;
}
关于卡信息文件
截图如下,每条卡信息占据一行
主要疑问如下:
既然已经利用fgets改变了文件指针位置,如果不利用fseek及ftell函数为何无法更新卡信息文件中的数据?
以下两个截图分别是利用fseek及ftell等函数和不利用的文件中数据截图
(以更改第二行卡号为qq的数据为例,注意##0##到##1##的转变)
1.更新成功!
2.更新失败!