我正在创建一个小程序,从串行端口接收(可能)多路串行数据,但在涉及读取和写入输出文件的此功能时遇到麻烦。
应该是这样的:[下面的代码片段]
在程序开始时,创建一个文件并插入:
DC1
DC2
DC3
DC4
JUNK:
~blah blah blah, COMport之类的事情发生了,我们得到一个包含一段数据的字符串~
我们来看看WriteToFile"函数,该函数有一段数据传递给它。(比如0.95)"NumberCheck"过滤所有非数字(但不包括'.')部分的数据(以防垃圾)。读取文件的每一行,将其长度添加到计数中,并检查哪个"zone"数据将进入。如果是正确的行,则停止读行,因为标记应该指向该行末尾的文件位置。(fs是一个故障安全计数器,以防发生奇怪的事情)。然后我找到从该位置到结束的文件的长度,调整temp以适应,用标记后的内容填充temp(包括该位置),并在标记处输出我的数据和temp…从理论上讲,将我的数据插入到正确的位置。
我遇到的问题是在第一次运行"WriteToFile"之后,fileline什么也没有出现,所以标记永远找不到它的位置。此外,即使在刷新文本文件之后,也没有显示任何更改的迹象(这是实现流的正确方法吗?)
相关代码如下:打开文件:
//opening file with the name in the textbox
string myfilename = txtboxCONT;
myfilename.append(".txt");
myfilename="test.txt"; //temporary name, DELETE BEFORE PUBLISH <<.
fstream myfile(myfilename,ios::in | ios::out | ios::trunc);
if (!myfile.is_open())
throw;
//initial file set-up
int i;
for (i=1;i<=4;i++)
myfile << "DC" << i << "n";
myfile << "JUNK:";
myfile.flush();
和我的写作功能:
void WriteToFile(fstream &myfile, string& data, int zone)
{
data = NumberCheck(data); //filters out non-numeric data, returns "null" if nothing left.
if (data=="null") //if the filter leaves no valid output, no need to write.
return;
myfile.seekg(0); //set initial position at the start?
string fileline, srch, out;
stringstream ss; //for int to string conversion
ss << zone;
srch="DC";
srch.append(ss.str());
int fs=1, marker=0;
while(fs<=4) //test each line if it beins with DC(zone)
{
getline(myfile, fileline);
marker = marker + fileline.length() + 1;
if (srch==fileline.substr(0,3))
break;
fs++;
}
if (fs!=5)
{
//can't avoid overwriting so... this is gon' suck...
string temp;
myfile.seekg(0,ios::end);
int length = myfile.tellg();
length = length - marker;
temp.resize(length);
myfile.seekg(marker);
myfile.read(&temp[0],temp.size());
myfile.seekp(marker);
myfile << ',' << data << temp;
}
else
{
myfile.seekp(0,ios::end);
myfile << ',' << data;
}
myfile.flush();
data.clear();
}
为什么不用string::find
,找出DC1、DC2、DC3呢?
看一下字符串库
顺便说一下,我不能对你的问题发表评论。你应该这样做:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
void WriteToFile(fstream &myfile, string& data, int zone)
{
string fileline, srch;
stringstream ss; //for int to string conversion
ss << zone;
srch="DC";
srch.append(ss.str());
int offset;
while(!myfile.eof())
{
getline(myfile, fileline);
if ((offset = fileline.find(srch, 0)) != string::npos)
{
cout << "My search " << srch << endl;
}
}
myfile.clear();
myfile.seekg(0, ios::beg);
// Write here
}
int main()
{
string myfilename = "test";
myfilename.append(".txt");
myfilename="test.txt"; //temporary name, DELETE BEFORE PUBLISH <<.
fstream myfile(myfilename,ios::in | ios::out | ios::trunc);
if (!myfile.is_open())
throw;
//initial file set-up
int i;
for (i=1;i<=4;i++) myfile << "DC" << i << "n";
myfile << "JUNK:";
myfile.flush();
string write = "blalblablab";
WriteToFile(myfile, write, 1);
WriteToFile(myfile, write, 2);
WriteToFile(myfile, write, 3);
WriteToFile(myfile, write, 4);
getchar();
return 0;
}