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;
}

 

 

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值