关于用fstream进行文件操作的疑问???

bailingke 2002-09-07 04:26:41
各位大虾好:
在下遇到一文件操作的问题,具体描述如下:
今有某单位提供给我方一数据文件,格式是这样的:第一行是字符串,说明变量名,
从第二行开始存放数据,每个时刻存放一行数据.每个时刻共有129个数据.
经我打开文件后,发现此文件有问题,有很多行的数据完全相同,估计是其他单位
的数据存取时间和我们要求的不一致,因而出现这种情况.
现在我想做到的事情是这样的:希望能把相同的行合并为一行.我的思路是这样的:用fstream中的getline取相临的行,并加以比较,相同的就抛弃,不同的就存入一个
新的文件中.
请各位大虾指点一下,我的思路是否正确?具体用什么函数操作??
多谢!!!
...全文
29 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
bailingke 2002-09-13
  • 打赏
  • 举报
回复
感谢各位的关注,确实给在下很多启发!
结帖!接分!
bailingke 2002-09-11
  • 打赏
  • 举报
回复
谢谢各位的指点
由于本人上网不方便
所以现在才看到
等在下回去试试
有了体会以后,再结帖!
programeer 2002-09-08
  • 打赏
  • 举报
回复
if(in.fail())
{
cout<<"Open File Failure!\n";
in.close();////////////////这里加上这个
exit(1);
}
dsangvei 2002-09-07
  • 打赏
  • 举报
回复
programeer的主意很好
nk_rainfall 2002-09-07
  • 打赏
  • 举报
回复
文件的关闭在两个对象的析构中会自动进行。
programeer 2002-09-07
  • 打赏
  • 举报
回复
我觉得可以把整个文件放在vector<string>中.对于每一个要添加的数据进行检查,看是否在string中.如果不在,则添加到vector<string>中.否则,读下一行的数据.

#include<iostream>
#include<string>
#include<fstream>
#include<cstdlib>
#include<vector>
using namespace std;
bool Index(string Substr,string Str);

void main()
{
vector<string> str;
ifstream in("FilePath1");//open for reading
if(in.fail())
{
cout<<"Open File Failure!\n";
exit(1);
}
string line;
ofstream out("FilePath2",ios::app);//以追加模式打开待写文件,for writing

while(getline(in,line))
{
bool exist;
str.push_back(line);
for(int j=0;j<str.size();j++)
if(!exist=Index(line,str[j]))//如果新数据不在原数据串中
str.push_back(line); //加入到str中
out<<line<<endl;
}
in.close();
}
out.close();
}

bool Index(string Substr,string Str) //Substr是否在Str中,在则返回true,否则返回false.
{
int SubLength=Substr.size();
int StrLength=Str.size();
for(int i=0;i<StrLength-SubLength+1;i++)
{
if(Substr==Str.substr(i,SubLength))
return true;
}
return false;
}
liubear 2002-09-07
  • 打赏
  • 举报
回复
上面所说,基本到位,最后close file
nk_rainfall 2002-09-07
  • 打赏
  • 举报
回复
你的想法基本可以,可以参见以下下面的伪码(没编译试过)

#include <fstream>
#include <string>
#include <iostream>
using namespace std;

char Buf[1024];

int main()
{
ifstream in_file("Your file path");
ofstream out_file("Your Output path");
string sOldLine;
while(in_file.getline(Buf, 1024))
{
string temp = Buf;
if (sOldLine == temp)
{
continue;
}
else
{
out_file << temp << endl;
sOldLine = temp;
}
}
return 0;
}
codingcoding 2002-09-07
  • 打赏
  • 举报
回复
非要用c写吗。Awk和Python好象更简单。
bailingke 2002-09-07
  • 打赏
  • 举报
回复
请各位抽空指点一下!谢谢了!

69,364

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧