次のファイルの内容を検討してください
[channels]
usecallerid=yes
cidsignalling=dtmf
cidstart=dtmf
;group=0
usecallerid=yes
context=pstn-channels
channel=>5
;group=0
usecallerid=yes
context=pstn-channels
channel=>6
;group=0
usecallerid=yes
context=pstn-channels
channel=>7
;group=1
context=phone-channels
channel=>1-4
チャネルを検索して、そのチャネルのいくつかのプロパティを C++ で変更したいだけです。ポイントは、各チャンネルのプロパティが「channel」キーワードの上に書かれていることです。たとえば、チャネル 5 のコンテキスト プロパティを phone に変更する必要があります。どうすればそうできますか?
編集:
だから私はついに方法を見つけました。「group」キーワードを探してファイルを 1 行ずつ読み取り、このキーワードに到達した後、「channel」キーワードを含む行に到達するまで、各行を文字列ベクトルにプッシュバックし始めます。次に、最後の行を「=」区切り文字で分割し、セル番号 1 と「portNumber」を比較し、一致する場合は文字列ベクトル (「group」で始まり「channel」キーワードで終わるデータ ブロック) を検索します。ユーザーが変更したいプロパティについては、このプロパティを見つけた後、seekg関数でファイルのポインタ位置を変更するための適切な量のオフセットを計算してから、データを書き込みます。しかし、問題は各行の文字数が限られていることです。つまり、長い行を挿入した場合、他の行が見逃されます。
;group=0
usecallerid=yes
context=pstn-channels
channel=>131
この行を「context=phone-channels」のようなものに変更したい場合、結果は次のようになります
;group=0
usecallerid=n
context=phone-channels
channel=>130
ご覧のとおり、2 行目の値が間違っています。編集する前に各行の最後にスペースを追加すると便利だと思いましたが、これは効率的な解決策ではないと思います。それで、あなたはどう思いますか?質問と問題が明確になることを願っています... .
そして、ここにコードがあります
bool changeConfigFiles(string addr, int portNumber, string key, string value)
{
//
char cmd[200];
fstream targetFile(addr.c_str());
string lines;
int offset=0,pPosition;
vector<string> helper,anotherHelper;
vector<string> contentsBlock;
//
if (!targetFile.is_open())
{
return false;
}
//
while(getline(targetFile, lines))
{
if(lines.find("group") != string::npos)
{
pPosition = targetFile.tellg();
pPosition -= lines.length();
contentsBlock.push_back(lines);
while(getline(targetFile, lines))
{
if(lines.find("=>") != string::npos)
{
helper = explode("=>",lines);
contentsBlock.push_back(lines);
break;
}
contentsBlock.push_back(lines);
}
}
//
if(helper.size() !=0 && strToInt(helper[1]) == portNumber)
{
for(int i=0;i<contentsBlock.size();i++)
{
if(contentsBlock[i].find(key) != string::npos)
{
anotherHelper = explode("=",contentsBlock[i]);
targetFile.seekg(pPosition+offset-1);
targetFile << endl << anotherHelper[0] << "=" << value << endl;
}
offset += contentsBlock[i].length();
}
//
helper.clear();
targetFile.seekg(pPosition+offset);
}
contentsBlock.clear();
}
targetFile.close();
return true;
}