C文件操作之写入统计信息到文件头
有一个小需求,文本文件存储的10几个字段,包括用户信息,产品信息,和价格信息,每个字段用符号'|'隔开,比如9962519126|20120524143922|Umai:PROG/330664@BESTV.SMG.SMG|城中大盗[英]|null|80|0|5|90002|0|2012052414412604|1|0|0
要求第一行是记录数|费用总和
实现方式为:当组合完所要写入文件的信息后,先把记录数加1,费用相加,写入第一行,然后把游标定位在文件当前末尾,再写入信息内容。以此进行循环!
简单代码为:
#include "stdafx.h"
#include<stdio.h>
#include<string>
int main(int argc, char* argv[])
{
char Inf[3][20] = {0};
char strs[3][10];
int i=0;
int iFeeSum = 0;
int iCount = 0;
int index = 0;
char lz_Recond[20] = {0};
char temp[20] = {0};
//用户名称|产品名称|费用
strcpy(Inf[0],"you|90002|100/n");
strcpy(Inf[1],"me|90003|100/n");
strcpy(Inf[2],"she|90004|100/n");
printf("inf=%s/n",Inf[0]);
FILE* fp= fopen("Record.txt","w" );
if ( fp == NULL )
{
printf("Can not open MdnFile :%s/n" );
exit( -1 );
}
printf("inf=%s/n",Inf[i]);
while(i < 3)
{
strcpy(temp, Inf[i]);
char *p = strtok(temp, "|"); //分离出需要的字段
while(p != NULL)
{
strcpy(strs[index],p);
p = strtok(NULL, "|");
index++;
}
iFeeSum = iFeeSum+atoi(strs[2]);
iCount = iCount + 1;
index = 0;
sprintf(lz_Recond,"%d|%d/n",iFeeSum,iCount);
printf("lz_Recond=%s/n",lz_Recond);
rewind(fp); //游标定位在文件头
fputs(lz_Recond, fp);
fseek(fp,0,SEEK_END); //游标定位在文件当前位置
printf("inf=%s/n",Inf[i]);
fputs(Inf[i],fp);
i++;
}
fclose(fp);
return 0;
}
摘自 cancan8538的专栏