设为首页 加入收藏

TOP

C文件写入统计信息到文件头
2013-09-24 09:18:45 来源: 作者: 【 】 浏览:111
Tags:文件 写入 统计 信息

  有一个小需求,文本文件存储的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 [20] = {0};

  char strs ;

  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 ,"me|90003|100\n");

  strcpy(Inf ,"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 );

  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;

  }

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇c语言strcpy()用法 下一篇C语言求解数独

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: