Chinaunix首页 | 论坛 | 博客
  • 博客访问: 749109
  • 博文数量: 116
  • 博客积分: 923
  • 博客等级: 准尉
  • 技术积分: 1635
  • 用 户 组: 普通用户
  • 注册时间: 2011-10-06 21:43
个人简介

一直帮老板搬运代码!!!

文章分类
文章存档

2013年(47)

2012年(69)

分类: C/C++

2012-11-09 12:04:30

修改文件某条记录的方式,除了一下方式外,还可以使用c++大学教程里面所说的fstream的方式
但是fstream方式非常不好用,体现在两个方面:一、在第一次seekp后是正确的,当修改某条记录后
再次seekp,就会发现位置不正确,可能不起作用了。第二、同一个 fstream insertInFile,第一次open
没问题,当某个原因,在同一程序关闭close后,再次open同一个文件,就会返回错误。同时还可能有其他问题,因此 fstream 方式非常不好用!没有下面的稳定,但是它的思路非常好,使用对象方式确定seek大小,以下就采用这种方式实现!
 
 
// ytest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
struct mystruct{
 int i;
 int b;
 int c;
} abc;
void ReadAll(FILE *mf)
{
 mystruct cdf;
 while((fread(&cdf,sizeof(mystruct),1,mf))>0)
 {
  cout << " 11 " <<  cdf.i << " 1b " <<  cdf.b << " c " <<  cdf.c<< endl;
 }
}

FILE * fd = NULL;
/************************************************************************/
/* 读取和创建配置文件,用于建立日志信息                                                                     */
/************************************************************************/
bool ReadConfig()
{
 if ( fd)
 {
  //获取文件中一行
  ReadAll(fd);
  //修改第五行
  fseek(fd,(5-1) * sizeof(mystruct),SEEK_SET);
  abc.i = 11;
  abc.b = 21;
  abc.c = 31;
  if(fwrite(&abc, sizeof(mystruct), 1, fd) != 1)
   cout << "file write error.\n"<< endl;
  fflush(fd);
  fseek(fd,0,SEEK_SET);
  ReadAll(fd);
  fclose(fd);
 }
 return true;
}
 
/************************************************************************/
/* 写入日志文件,记录相应配置信息                                                                     */
/************************************************************************/
bool WriteConfig()
{
 abc.i = 1;
 abc.b = 2;
 abc.c = 3;
 //清空文件
 if ((fd = fopen("abc.txt","w+")) != NULL)//把是本表的数据去掉
 {
  
  for (int i = 0 ; i < 10; i++)
  {
   abc.i = i;
   abc.b = i;
   if(fwrite(&abc, sizeof(mystruct), 1, fd) != 1)
    cout << "file write error.\n"<< endl;
  }
  
 }
 //保存新记录
 fflush(fd);
 fseek(fd,0,SEEK_SET);
 return true;
}
int main()
{
 WriteConfig();
 ReadConfig();
 return 0;
}

 
阅读(2379) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~