读书人

关于c++的资料读写修改删除

发布时间: 2012-08-30 09:55:54 作者: rapoo

关于c++的文件读写,修改,删除。
各位大神帮忙啊,目前情况是这样的,我要将一些对象的各个值写入文本文档,之后,要能实现文本文档的定位删除(删除特定对象的值),定位修改(修改特定对象的值),这个怎么实现啊?
class spbase
{
public: int t;
float oprice;
float iprice;
float prof;
int quantity;
char name[30];
void getdate();
void showdate();
void add();
void search();
void remove();
int gett(){return t;}
}; 对象是这个类定义的。

[解决办法]
直接写出去就行了, fwrite(&object, 1, sizeof(spbase), fp)。

先操作第n个就fseek(fp, (n - 1) * sizeof(spbase), SEEK_SET);
[解决办法]
头文件
#ifndef _CWRFILE_
#define _CWRFILE_
#endif

#include <fstream>
#include <string>
#include <iostream>
#define FILENAME "out.txt"
using namespace std;
class Cwrfile
{
public:
Cwrfile(void);
~Cwrfile(void);

/*创建文件*/
void CreateFile();

/*写文件*/
int WriteFile(std::string writeStr);

/*读文件*/
string ReadFile();


/*删除指定的位置*/
string DeletePos(int pBegin, int pEnd);

/*删除特定字符*/
string DeleteSpecific(string deleteStr,string fullStr);

/*运行所有*/
void Cwrfile::run();

private:
string fileName ;
ofstream out;
ifstream in;
string lastStr;
string fullStr;
};

//cpp
#include "Cwrfile.h"

Cwrfile::Cwrfile(void)
{
fileName = "out.txt";
}

Cwrfile::~Cwrfile(void)
{
}


/*创建文件*/
void Cwrfile::CreateFile()
{

out.open(fileName.c_str()) ;
if (!out)
{
cout<<"open error"<<endl;
}


}

/*写文件*/
int Cwrfile::WriteFile(string writeStr)
{

if( out<< writeStr )
{
out.close();
return 0;
}
else
{

return -1;
}

}

/*读文件*/
string Cwrfile::ReadFile()
{

in.open(fileName.c_str());

for(string getStr; getline(in,getStr);)
{
fullStr += getStr;
}
return fullStr;

}

/*删除指定的位置*/
string Cwrfile::DeletePos(int pBegin, int pEnd)
{

string fullStr = ReadFile();
int fullStrLen = fullStr.length();
string lastStr = fullStr.substr(0,pBegin) + fullStr.substr(pEnd,fullStrLen);
return lastStr;
}

/*删除特定字符*/
string Cwrfile::DeleteSpecific(string deleteStr,string fullStr)
{


int fullStrLen = fullStr.length();
/*用来标记第一次文件是否存在deleteStr*/
static int flg = 0;


if (string::npos != fullStr.find(deleteStr,0) )
{

int beginPos = fullStr.find( deleteStr,0);
int lenthDelete = deleteStr.length();
lastStr = fullStr.substr(0,beginPos);
lastStr = lastStr + fullStr.substr(beginPos+lenthDelete +1);
lastStr = DeleteSpecific(deleteStr, lastStr);
flg = 1;

}
else if(flg == 0)
{
//cout<<"can't find the deleteStr";

}

return lastStr;

}

void Cwrfile::run()
{
CreateFile();

int resultNum = WriteFile("hello hello this is a demo");
if( -1 == resultNum)
{

cout<<"writefile error\n";
}
cout<<DeletePos(10, 12)<<endl;
string fullStr = ReadFile();
cout<<DeleteSpecific("hello",fullStr)<<endl;
}
//你在main函数申请一个对象 Cwrfile::run()
------解决方案--------------------


man pread
man pwrite
[解决办法]
所谓修改删除文件a某位置的内容,其实是读打开文件a,再将‘a中修改删除位置之前的内容+修改删除的内容+a中修改删除位置之后的内容’保存到文件b,关闭文件a,删除文件a,将文件b改名为与之前文件a相同的名字,仅此而已。

读书人网 >C++

热点推荐